<template>
  <div style="position: relative">
    <div class="w-form-header">
      <div class="header">
          <div style="display:flex" v-if="!version&&userStore.userInfo.authority?.authorityId !== 1000">
            <template v-if="isView != 1">
              <div v-if="type == 'create'">
                <el-button type="primary" @click="saveAsDraft('保存')">保存</el-button>
                <el-button type="success" @click="saveAsDraft('提交')">提交</el-button>
              </div>
              <div v-if="type == 'update'&&formData.status">
                <div v-if="formData.status == '草稿'">
                  <el-button type="primary" @click="saveAsDraft('保存')">保存</el-button>
                  <el-button type="success" @click="saveAsDraft('提交')">提交</el-button>
                  <!-- <el-button
                type="primary"
                @click="print"
                :loading="printBtnLoading"
                >打印</el-button
              > -->
                </div>
                <div v-else-if="formData.status == '已確認'">
                  <!-- 按钮叫保存,实际是提交功能 -->
                  <el-button type="primary" @click="saveAsDraft('保存', '提交')">保存</el-button>

                  <el-button type="primary" @click="toSap">汇入SAP</el-button>
                </div>
                <div v-else-if="formData.status == '已匯入SAP'"> 
                <el-button type="success" @click="subAndopenDialog">修改</el-button>              <!-- <el-button
                type="primary"
                @click="print"
                :loading="printBtnLoading"
                >打印</el-button
              > -->
            </div>
              </div>
            </template>
            <template v-else-if="isView == 1 && formData.status != '已匯入SAP'">
              <el-button type="primary" @click="formEdit">编辑</el-button>
            </template>
            <div v-else-if="isView == 1 && formData.status == '已匯入SAP'">
              <el-button type="success" @click="subAndopenDialog">修改</el-button>
              <!-- <el-button
                type="primary"
                @click="print"
                :loading="printBtnLoading"
                >打印</el-button
              > -->
            </div>
            <el-button type="primary" style="margin-left:10px" @click="print" v-if="type != 'create'"
              :loading="printBtnLoading">导出</el-button>

            
          </div>
          <div v-else></div>
          <span v-auth="btnAuth.sapParam" v-if="type != 'create'" style="flex:1">
            <el-select v-model="sapParam.factoryCode" placeholder="请选择" style="width: 80px; margin-left: 10px">
              <el-option :label="'1000'" :value="'1000'" />
              <el-option :label="'9000'" :value="'9000'" />
            </el-select>
            <el-select v-model="sapParam.steps" placeholder="请选择" style="width: 120px; margin-left: 10px">
              <el-option v-for="item in sapParam.stepList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            <el-button @click="getParams" style="margin-left: 10px">下载参数</el-button>
          </span>
          <div class="title-box" v-if="type == 'update'">
            <span class="version"> 版本: {{ detail.version || "暂无" }}</span>
            <span class="status">{{ formData.status }}</span>
          </div>

      </div>
    </div>
    <div class="gva-form-box admin-content">
      <div class="form-box">
        <div>
          <div class="gva-form-box">
            <div class="w-form-box">
              <div class="list-header">
                基本资料

                <el-button type="primary" @click="baseTongbu('手动')" :disabled="isView == 1">同步</el-button>
              </div>
              <div v-if="(type == 'update' &&
                formData.styleNum &&
                styleNumSelectDetail) ||
                type == 'create'
                ">
                <el-descriptions title=" " border :column="4">
                  <el-descriptions-item label="款式编号" v-if="type == 'update'">
                    <span>{{ formData.styleNum }}</span>
                  </el-descriptions-item>
                  <el-descriptions-item label="款式编号" v-else>
                    <div style="
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                      ">
                      <el-select v-model="formData.styleNum" placeholder="请选择"
                        style="min-width: 120px; margin-right: 10px" filterable remote
                        :remote-method="remoteMethodProjectStyles" @change="productStylesChange">
                        <el-option v-for="item in productStylesList" :key="item.styleNum" :label="item.styleNum"
                          :value="item.styleNum" />
                      </el-select>
                      <el-icon @click="openCreateAndEdit">
                        <Search />
                      </el-icon>
                    </div>
                  </el-descriptions-item>

                  <el-descriptions-item label="主原料">
                    <el-select v-model="formData.mainMaterial" placeholder="请选择" style="min-width: 150px"
                      :disabled="isView == 1">
                      <el-option v-for="item in mainMaterialList" :key="item.value" :label="item.label"
                        :value="item.value" />
                    </el-select>
                  </el-descriptions-item>

                  <el-descriptions-item label="镜架镜片">
                    <el-select v-model="formData.category" :placeholder="`请选择`" style="min-width: 150px" :clearable="true"
                      filterable :disabled="isView == 1">
                      <el-option v-for="(item, index) in dictOptions.styleCate" :key="index" :label="item.label"
                        :value="item.value" />
                    </el-select>
                  </el-descriptions-item>

                  <el-descriptions-item label="成本核算分类">
                    <el-select v-model="formData.costAccountCate" :placeholder="`请选择`" style="min-width: 150px"
                      :clearable="true" filterable :disabled="isView == 1">
                      <el-option v-for="(item, index) in dictOptions.costAccountCate" :key="index" :label="item.label"
                        :value="item.value" />
                    </el-select>
                  </el-descriptions-item>

                  <el-descriptions-item label="本厂款号">{{
                    styleNumSelectDetail.localStyleNum
                  }}</el-descriptions-item>

                  <el-descriptions-item label="性别">
                    <el-select v-model="formData.gender" :placeholder="`请选择`" style="min-width: 150px" :clearable="true"
                      filterable :disabled="isView == 1">
                      <el-option v-for="(item, index) in dictOptions.productGender" :key="index" :label="item.label"
                        :value="item.value" />
                    </el-select>
                  </el-descriptions-item>

                  <el-descriptions-item label="发行年">
                    <el-select v-model="formData.issuanceYear" :placeholder="`请选择`" style="min-width: 150px"
                      :clearable="true" filterable :disabled="isView == 1">
                      <el-option v-for="(item, index) in dictOptions.issuanceYear" :key="index" :label="item.label"
                        :value="item.value" />
                    </el-select>
                  </el-descriptions-item>

                  <el-descriptions-item label="脾头切口位">
                    <el-select v-model="formData.splenicHeadIncisionPosition" :placeholder="`请选择`"
                      style="min-width: 150px" :clearable="true" filterable :disabled="isView == 1">
                      <el-option v-for="(
                          item, index
                        ) in dictOptions.splenicHeadIncisionPosition" :key="index" :label="item.label"
                        :value="item.value" />
                    </el-select>
                  </el-descriptions-item>

                  <el-descriptions-item label="SBU">{{
                    productSpec.sbuNum
                  }}</el-descriptions-item>

                  <el-descriptions-item label="镜架结构"><el-select v-model="formData.frameCate" :placeholder="`请选择`"
                      style="min-width: 150px" :clearable="true" filterable :disabled="isView == 1">
                      <el-option v-for="(item, index) in dictOptions.frameCate" :key="index" :label="item.label"
                        :value="item.value" />
                    </el-select>
                  </el-descriptions-item>

                  <el-descriptions-item label="发行月">
                    <el-select v-model="formData.issuanceMonth" :placeholder="`请选择`" style="min-width: 150px"
                      :clearable="true" filterable :disabled="isView == 1">
                      <el-option v-for="(item, index) in dictOptions.issuanceMonth" :key="index" :label="item.label"
                        :value="item.value" />
                    </el-select>
                  </el-descriptions-item>

                  <el-descriptions-item label="铰链类别">
                    <el-select v-model="formData.hingeType" :placeholder="`请选择`" style="min-width: 150px"
                      :clearable="true" filterable :disabled="isView == 1">
                      <el-option v-for="(item, index) in dictOptions.hingeType" :key="index" :label="item.label"
                        :value="item.value" />
                    </el-select>
                  </el-descriptions-item>

                  <el-descriptions-item label="客户编号">{{
                    productSpec.cumstomerNum
                  }}</el-descriptions-item>

                  <el-descriptions-item label="镜架材质">{{
                    productSpec.frameMaterials
                  }}</el-descriptions-item>

                  <el-descriptions-item label="物料群组">
                    <!-- <el-select
                      v-model="formData.materialGroup"
                      placeholder="请选择"
                      v-if="
                        productSpec.cumstomerNum &&
                        getGroup().split(',').length > 1
                      "
                      :disabled="isView == 1"
                      style="width: 90%"
                    >
                      <el-option
                        v-for="item in getGroup().split(',')"
                        :label="item"
                        :value="item"
                      />
                    </el-select> -->
                    <span>
                      {{ formData.materialGroup }}
                    </span>
                  </el-descriptions-item>

                  <el-descriptions-item label="创建时间">
                    {{
                      detail.CreatedAt
                      ? formatDate(detail.CreatedAt, "yyyy-MM-dd hh:mm:ss")
                      : ""
                    }}</el-descriptions-item>

                  <el-descriptions-item label="客户款号">{{
                    styleNumSelectDetail.customerStyleNum
                  }}</el-descriptions-item>

                  <el-descriptions-item label="中金架类">{{
                    productSpec.metalFrameCate
                  }}</el-descriptions-item>

                  <el-descriptions-item v-if="!formData.status || formData.status == '草稿'" :label="productSpec.cumstomerNum == 'ST101' ? '基本物料' : ''
                    ">
                    {{
                      productSpec.cumstomerNum == "ST101"
                      ? styleNumSelectDetail.customerStyleNum
                      : ""
                    }}
                  </el-descriptions-item>
                  <el-descriptions-item v-else :label="productSpec.cumstomerNum == 'ST101' ? '基本物料' : ''
                      ">
                    {{ detail.basicMaterial || "" }}
                  </el-descriptions-item>

                  <el-descriptions-item label="创建人">
                    <span v-if="detail.createdUser && detail.createdUser.nickName">
                      {{ detail.createdUser.nickName }}
                    </span>
                    <span v-else>{{ detail.createUesr }}</span>
                  </el-descriptions-item>

                  <el-descriptions-item label="品牌">{{
                    styleNumSelectDetail.customerBrand || ""
                  }}</el-descriptions-item>

                  <el-descriptions-item label="存储位置"><el-input :maxlength="20" v-model="formData.storageLocation"
                      placeholder="请输入" disabled /></el-descriptions-item>

                  <el-descriptions-item label="单位">
                    <el-input :maxlength="20" v-model="formData.unit" placeholder="请输入" :disabled="isView == 1" />
                  </el-descriptions-item>

                  <el-descriptions-item label="更新时间">
                    {{
                      detail.UpdatedAt
                      ? formatDate(detail.UpdatedAt, "yyyy-MM-dd hh:mm:ss")
                      : ""
                    }}
                  </el-descriptions-item>
                  <el-descriptions-item label="第一版本创建时间" v-if="route.query.ID">
                     <span v-if="detail.FirstCreatedAt">
                      {{formatDate(detail.FirstCreatedAt )=="1-01-01" ? '' : formatDate(detail.FirstCreatedAt ) }}
                    </span>
                  </el-descriptions-item>
                  <el-descriptions-item label="系列">{{
                    styleNumSelectDetail.series
                  }}</el-descriptions-item>
             

                  <el-descriptions-item label="物料描述">
                    <el-input :disabled="isView == 1" :maxlength="30" v-model="formData.materialDesc" placeholder="请输入" />
                  </el-descriptions-item>

                  <el-descriptions-item v-if="!formData.status || formData.status == '草稿'" :label="productSpec.cumstomerNum == 'ST101' ||
                    productSpec.customerBrand == 'LEVIS' ||
                    productSpec.customerBrand == 'levis' ||
                    productSpec.customerBrand == 'fila' ||
                    productSpec.customerBrand == 'FILA'
                    ? '标准说明'
                    : ''
                    ">
                    {{
                      productSpec.cumstomerNum == "ST101"
                      ? styleNumSelectDetail.series
                      : productSpec.customerBrand == "LEVIS" ||
                        productSpec.customerBrand == "levis" ||
                        productSpec.customerBrand == "fila" ||
                        productSpec.customerBrand == "FILA"
                        ? productSpec.customerBrand
                        : ""
                    }}</el-descriptions-item>
                  <el-descriptions-item v-else :label="productSpec.cumstomerNum == 'ST101' ? '标准说明' : ''
                        ">
                    {{ detail.standardDesc }}</el-descriptions-item>
                  <el-descriptions-item label="更新人">
                    <span v-if="detail.updatedUser && detail.updatedUser.nickName">
                      {{ detail.updatedUser.nickName }}
                    </span>
                    <span v-else>{{ detail.updateUser }}</span>
                  </el-descriptions-item>
                </el-descriptions>
                <el-form-item label="内部备注：" style="
                    display: flex;
                    align-items: center;
                    width: 100%;
                    margin-top: 20px;
                  ">
                  <el-input disabled type="textarea" autosize v-model="formData.internalNote" :clearable="true"
                    placeholder="自定义填写" />
                </el-form-item>
              </div>
            </div>
          </div>

          <div v-if="formData.styleNum">
            <div class="gva-form-box">
              <div class="w-form-box">
                <div class="list-header">
                  物料特性
                  <el-button type="primary" @click="syncWuLiaoTeXing('手动')" :disabled="isView == 1">同步</el-button>
                </div>
                <div>
                  <el-table :data="wuliaotexingList" style="width: 100%" border>
                    <el-table-column prop="colorNum" label="颜色">
                    </el-table-column>
                    <el-table-column prop="" label="内文">
                      <template #default="scope">
                        <a href="javascript:" @click="watchInnerText(scope.row)">查看</a>
                      </template>
                    </el-table-column>
                    <el-table-column prop="customerColorNum" label="客色号">
                    </el-table-column>
                    <el-table-column prop="customerStyleNum" label="客款号">
                    </el-table-column>
                    <el-table-column prop="localStyleDesc" label="本厂颜色描述" min-width="100">
                    </el-table-column>
                    <el-table-column prop="brand" label="品牌">
                    </el-table-column>
                    <el-table-column prop="colorDesc" label="颜色描述" v-if="productSpec.cumstomerNum == 'ST101' ||
                      productSpec.customerBrand == 'LEVIS' ||
                      productSpec.customerBrand == 'levis' ||
                      productSpec.customerBrand == 'fila' ||
                      productSpec.customerBrand == 'FILA'
                      ">
                      <template #default="scope">
                        <el-input :maxlength="30" v-model="scope.row.colorDesc" :clearable="true" placeholder="请输入"
                          :disabled="isView == 1" />
                      </template>
                    </el-table-column>
                    <el-table-column prop="packageNum" label="包装形式号">
                      <template #default="scope">
                        <el-input :maxlength="30" v-model="scope.row.packageNum" :clearable="true" placeholder="请输入"
                          :disabled="isView == 1" />
                      </template>
                    </el-table-column>
                    <el-table-column prop="salesNum" label="销售组织" width="130" v-if="productSpec &&
                      productSpec.cumstomerNum != 'ST101' &&
                      (productSpec.customerBrand == 'LEVIS' ||
                        productSpec.customerBrand == 'levis' ||
                        productSpec.customerBrand == 'fila' ||
                        productSpec.customerBrand == 'FILA')
                      ">
                      <!-- <template #default="scope">
                        <el-select
                          v-model="scope.row.salesNum"
                          placeholder="请选择"
                          multiple
                          style="width: 100%"
                          :disabled="isView == 1"
                          v-if="
                            scope.row.colorNum.indexOf('Y') < 0 && isView != 1
                          "
                        >
                          <el-option label="1000" value="1000" />
                          <el-option label="9000" value="9000" />
                        </el-select>
                      </template> -->
                    </el-table-column>
                  </el-table>
                  <el-table :data="wuliaotexingList2" style="width: 100%" border>
                    <el-table-column prop="sizeNum" label="尺码" width="250px">
                    </el-table-column>
                    <el-table-column prop="clientSizeDesc" label="客户尺码描述">
                      <template #default="scope">
                        <el-input :maxlength="18" v-model="scope.row.clientSizeDesc" :clearable="true" placeholder="请输入"
                          :disabled="isView == 1" />
                      </template>
                    </el-table-column>
                    <el-table-column prop="localSizeDesc" label="本厂尺码描述">
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </div>
            <div class="gva-form-box" v-if="productSpec.cumstomerNum == 'ST101' ||
              productSpec.customerBrand == 'LEVIS' ||
              productSpec.customerBrand == 'levis' ||
              productSpec.customerBrand == 'fila' ||
              productSpec.customerBrand == 'FILA'
              ">
              <div class="w-form-box">
                <div class="list-header">
                  {{
                    productSpec.cumstomerNum == "ST101"
                    ? "ST101"
                    : productSpec.customerBrand == "LEVIS" ||
                      productSpec.customerBrand == "levis" ||
                      productSpec.customerBrand == "fila" ||
                      productSpec.customerBrand == "FILA"
                      ? `${productSpec.customerBrand}`
                      : ""
                  }}成品主档
                  <el-button type="primary" @click="getChengpinzhudangList('手动')" :disabled="isView == 1">同步</el-button>
                </div>
                <div>
                  <el-table :data="chengpinzhudangList" style="width: 100%" border>
                    <el-table-column prop="materialNum" label="物料编号">
                    </el-table-column>
                    <el-table-column prop="materialDesc" label="物料说明">
                    </el-table-column>
                    <el-table-column prop="materialGroup" label="物料群组">
                      <template #default="scope">
                        <div>
                          <el-select v-model="scope.row.materialGroup" :disabled="isView == 1">
                            <el-option :label="val" :value="val" v-for="val in getMaterialGroupOptions(scope.row)" />
                          </el-select>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column prop="standardDesc" label="标准说明">
                    </el-table-column>
                    <el-table-column prop="variableSettingColor" label="变式设定(color)">
                    </el-table-column>
                    <el-table-column prop="variableSettingSize" label="变式设定(size)">
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </div>

            <div :class="['gva-form-box', 'jianlishipipeijianzhudang', { 'fullscreen-handle1': fullscreenHandleShow }]">
              <div style="float:right;margin-right:20px;cursor: pointer;"
                @click="fullscreenHandleShow = !fullscreenHandleShow">
                <div class="gvaIcon gvaIcon-fullscreen-shrink" v-if="fullscreenHandleShow"></div>
                <div class="gvaIcon gvaIcon-fullscreen-expand" v-else></div>
              </div>
              <div class="w-form-box">
                <div class="list-header" style="display: flex; align-items: center">
                  士啤配件主档
                  <el-button type="primary" @click="syncShiPiPeiJianZhuDang('手动')" :disabled="isView == 1"
                    :loading="ShiPiPeiJianZhuDangLoading" style="margin-left: 10px">同步</el-button>
                  <el-button type="primary" :disabled="!currentRow || isView == 1"
                    @click="deleteRow(shipipeijianList, currentRow.ids)">删除</el-button>
                  <el-button type="primary" :disabled="isView == 1" @click="downloadTemplate"
                    style="margin-right: 10px">下载模板</el-button>

                  <el-upload :action="`${path}/masterBOMList/importExcel`" :on-error="uploadError" accept=".xlsx, .xls"
                    :before-upload="beforeUpload" :on-success="shipipeijianDataUploadSuccess" :data="{styleNum:formData.styleNum}" :headers="{
                      'x-token': xToken,
                      'x-user-id': xUserId,
                      Authorization: `Bearer ${xToken}`,
                    }" :show-file-list="false" class="upload-btn">
                    <el-button type="primary" :disabled="isView == 1">导入</el-button>
                  </el-upload>
                </div>
                <el-table :data="shipipeijianList" style="width: 100%" border default-expand-all row-key="ids"
                  highlight-current-row @current-change="handleCurrentChange">
                  <!-- <el-table-column type="selection" width="40" >
                    </el-table-column> -->
                  <el-table-column label="元件编号" min-width="170">
                    <template #default="scope">
                      <span v-if="scope.row.selfLevel == 1">
                        {{ scope.row.componentNum }}
                      </span>
                      <div v-else-if="scope.row.selfLevel == 2">
                        <el-input :maxlength="18" v-model="scope.row.componentNum" @blur="blurTest(scope.row)"
                          :clearable="true" placeholder="请输入" :disabled="isView == 1" />
                        <div v-if="scope.row.err" style="
                            font-size: 12px;
                            color: red;
                            line-height: normal;
                          ">
                          {{ scope.row.err }}
                        </div>
                      </div>
                      <!-- <el-select
                       
                        @change="componentNumChange($event, scope.row)"
                       
                        placeholder="请选择"
                        style="width: 100%"
                        filterable
                        remote
                        :remote-method="remoteMethodComponentNum"
                      >
                        <el-option
                          v-for="item in componentNumList"
                          :key="item.componentNum"
                          :label="item.componentNum"
                          :value="item.componentNum"
                        />
                      </el-select> -->
                      <el-input :maxlength="18" :disabled="isView == 1" @input="
                        remoteMethodComponentNum(
                          scope.row.componentNum,
                          scope.row
                        )
                        " v-model="scope.row.componentNum" :clearable="true" placeholder="请输入"
                        v-else-if="scope.row.selfLevel == 3" />
                    </template>
                  </el-table-column>
                  <el-table-column label="元件名称" min-width="120">
                    <template #default="scope">
                      <span v-if="scope.row.selfLevel == 1 || scope.row.selfLevel == 2
                        ">
                      </span>

                      <span v-else-if="scope.row.selfLevel == 3">
                        {{ scope.row.accessoryName }}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column label="ICT" min-width="80">
                    <template #default="scope">
                      <span v-if="scope.row.selfLevel == 1"></span>
                      <div v-else-if="scope.row.selfLevel == 2 || scope.row.selfLevel == 3
                        " style="flex: 1">
                        <el-select v-model="scope.row.lct" placeholder="请选择" v-if="scope.row.lctData == 'F'"
                          style="width: 90%" :disabled="isView == 1">
                          <el-option label="F" value="F" />
                          <el-option label="L" value="L" />
                        </el-select>
                        <span v-else>
                          {{ scope.row.lct }}
                        </span>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="物料群组" min-width="80">
                    <template #default="scope">
                      <span v-if="scope.row.selfLevel == 1"></span>
                      <div v-else-if="scope.row.selfLevel == 2" style="flex: 1">
                        <el-select v-model="scope.row.group" placeholder="请选择"
                          v-if="productSpec.cumstomerNum && scope.row.groupList" style="width: 90%"
                          :disabled="isView == 1">
                          <el-option v-for="item in scope.row.groupList" :label="item" :value="item" />
                        </el-select>
                        <span v-else-if="!scope.row.groupList &&
                          getGroup2(scope.row.componentNum)
                          ">
                          {{ scope.row.group }}
                        </span>
                        <el-input v-else-if="!getGroup2(scope.row.componentNum)" :maxlength="20" v-model="scope.row.group"
                          placeholder="请输入" :disabled="isView == 1" />
                      </div>
                      <span v-else-if="scope.row.selfLevel == 3">
                        {{ scope.row.group }}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column label="物料说明" min-width="150">
                    <template #default="scope">
                      <span v-if="scope.row.selfLevel == 1"></span>
                      <div v-else-if="scope.row.selfLevel == 2" style="flex: 1">
                        <el-input :maxlength="100" v-model="scope.row.sapDesc" :clearable="true" placeholder="请输入"
                          :disabled="isView == 1" />
                      </div>
                      <div v-else-if="scope.row.selfLevel == 3">
                        {{ scope.row.sapDesc }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="数量" min-width="80" align="center">
                    <template #default="scope">
                      <span v-if="scope.row.selfLevel == 1"></span>
                      <div v-else-if="scope.row.selfLevel == 2 || scope.row.selfLevel == 3
                        " style="flex: 1">
                        <span v-if="scope.row.isPack == '0'">
                          {{ scope.row.num }}
                        </span>
                        <el-input-number v-else :modelValue="scope.row.num" style="width: 100%" :max="1000" :min="0"
                          @update:modelValue="(newValue) => (scope.row.num = newValue.toString())
                            " stringMode :controls="false" :clearable="true" placeholder="请输入" @focus="handleFocus"
                          :disabled="isView == 1" />
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="单位" min-width="80">
                    <template #default="scope">
                      <span v-if="scope.row.selfLevel == 1"></span>
                      <div v-else-if="scope.row.selfLevel == 2" style="flex: 1">
                        <el-select v-model="scope.row.unit" placeholder="请选择" :disabled="isView == 1">
                          <el-option v-for="item in unitList" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                      </div>
                      <div v-else-if="scope.row.selfLevel == 3">
                        {{ scope.row.unit }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="标准说明" v-if="productSpec.cumstomerNum &&
                    productSpec.cumstomerNum == 'ST101'
                    ">
                    <template #default="scope">
                      <span v-if="scope.row.selfLevel == 1 || scope.row.selfLevel == 3
                        "></span>
                      <el-input v-else-if="scope.row.selfLevel == 2" :maxlength="20" v-model="scope.row.standardDesc"
                        :clearable="true" placeholder="请输入" :disabled="isView == 1" />
                    </template>
                  </el-table-column>
                  <el-table-column label="排序字串" min-width="100">
                    <template #default="scope">
                      <span v-if="scope.row.selfLevel == 1 || scope.row.selfLevel == 2
                        "></span>
                      <div v-else-if="scope.row.selfLevel == 3" style="flex: 1">
                        <el-select :disabled="isView == 1" v-model="scope.row.sortLetter" placeholder="请选择"
                          style="width: 100%" v-if="scope.row.selectList && scope.row.selectList.length
                            ">
                          <el-option v-for="item in scope.row.selectList" :key="item.ringOrFoot" :label="item.ringOrFoot"
                            :value="item.accessoryName" />
                        </el-select>
                        <span v-else>
                          {{ scope.row.sortLetter }}
                        </span>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="componentNum" label="操作" width="140" v-if="isView != 1">
                    <template #default="scope">
                      <div class="two" v-if="scope.row.selfLevel == 1">
                        <a href="javascript:" @click="levelOneAdd(scope.row)">新增</a>
                      </div>
                      <div v-else-if="scope.row.selfLevel == 2">
                        <a href="javascript:" style="margin-right: 8px" @click="addAccessory(scope.row)">加配件</a>
                        <el-popover placement="top" :width="160">
                          <p>请输入新增包装数量</p>
                          <div style="margin: 10px 0">
                            <el-input-number v-model="addNum" style="width: 100%" :max="100" :min="0" :precision="0"
                              :controls="false" :clearable="false" placeholder="请输入" :disabled="isView == 1" @focus="handleFocus"/>
                          </div>
                          <div style="text-align: right; margin: 0">
                            <el-button size="small" text @click="visible = false">取消</el-button>
                            <el-button size="small" type="primary" @click="addPackage(scope.row)">
                              确认
                            </el-button>
                          </div>
                          <template #reference>
                            <a href="javascript:" @click="visible = true" style="margin-right: 8px">加包装</a>
                          </template>
                        </el-popover>
                        <a href="javascript:" @click="deleteRow(shipipeijianList, scope.row.ids)">删除</a>
                      </div>
                      <div v-else-if="scope.row.selfLevel == 3">
                        <a href="javascript:" @click="deleteRow(shipipeijianList, scope.row.ids)">删除</a>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>

            <div class="gva-form-box" v-if="productSpec.frameMaterials != '膠架' &&
              productSpec.frameMaterials != '啤架' &&
              wuliaotexingList2.length
              ">
              <div class="w-form-box">
                <div class="list-header">
                  斋架主档
                  <el-button type="primary" @click="syncZhaiJiaZhuDang('手动')" :disabled="isView == 1">同步</el-button>
                </div>
                <div>
                  <el-table :data="zhaiJiaZhuDangList" style="width: 100%" border>
                    <el-table-column prop="lct" label="ICT" width="140px">
                      <template #default="scope">
                        <el-select v-model="scope.row.lct" placeholder="请选择" style="width: 100%" :disabled="isView == 1">
                          <el-option label="F" value="F" />
                          <el-option label="L" value="L" />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column prop="componentNum" label="元件编号" width="240px">
                    </el-table-column>
                    <el-table-column prop="group" label="物料群组" width="140px">
                      <template #default="scope">
                        <el-select v-model="scope.row.group" placeholder="请选择" style="width: 100%" :disabled="isView == 1"
                          v-if="scope.row.strategyGroupList">
                          <el-option label="30001" value="30001" />
                          <el-option label="30030" value="30030" />
                        </el-select>
                        <span v-else>
                          {{ scope.row.group }}
                        </span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="strategyGroup" label="策略群组" width="140px">
                      <template #default="scope">
                        <el-select v-model="scope.row.strategyGroup" placeholder="请选择" style="width: 100%"
                          :disabled="isView == 1">
                          <el-option label="10" value="10" />
                          <el-option label="20" value="20" />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column prop="num" label="数量" width="100">
                      <template #default="scope">
                        <el-input-number :modelValue="scope.row.num" style="width: 100%" :max="1000" :min="0"
                          :disabled="isView == 1" :precision="0" @update:modelValue="(newValue) => (scope.row.num = newValue.toString())
                            " stringMode :controls="false" :clearable="true" placeholder="请输入" @focus="handleFocus"/>
                      </template>
                    </el-table-column>
                    <el-table-column prop="unit" label="单位" width="100">
                      <template #default="scope">
                        <el-select v-model="scope.row.unit" placeholder="请选择" :disabled="isView == 1">
                          <el-option v-for="item in unitList" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column prop="materialDesc" label="物料说明">
                      <template #default="scope">
                        <el-input :maxlength="30" v-model="scope.row.materialDesc" :clearable="true" placeholder="请输入"
                          :disabled="isView == 1" />
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </div>

            <div class="gva-form-box" v-if="wuliaotexingList.length && wuliaotexingList2.length">
              <div class="w-form-box">
                <createBom ref="createBomRef" :zhaiJiaZhuDangList="zhaiJiaZhuDangList" :colors="wuliaotexingList"
                  :sizes="wuliaotexingList2" :formData="formData" :productSpecID="productSpec.ID"
                  :customerBrand="productSpec.customerBrand" :isView="isView"></createBom>
              </div>
            </div>

            <div class="gva-form-box">
              <div class="w-form-box">
                <div class="list-header">
                  Bom备注
                  <el-button type="primary" @click="asyncRemark" :disabled="isView == 1">同步产品规格备注</el-button>
                </div>
                <div>
                  <el-input v-model="notes[0].content" style="width: 100%" autosize type="textarea" :maxlength="1000"
                    placeholder="请输入" :disabled="isView == 1" />
                </div>
              </div>
            </div>

            <div class="gva-form-box">
              <div class="w-form-box">
                <div class="list-header">
                  Bom附件

                  <el-button type="primary" @click="openUploadDialog" :disabled="isView == 1">上传</el-button>
                </div>
                <div>
                  <el-table :data="BOMFileList" border style="width: 100%">
                    <el-table-column label="描述" prop="desc" width="400">
                      <template #default="scope">
                        <el-input :maxlength="100" v-model="scope.row.desc" :clearable="true" placeholder="请输入" />
                      </template>
                    </el-table-column>
                    <el-table-column label="附件文件" prop="fileUrl" width="300">
                      <template #default="scope">
                        <a href="javascript:" @click.stop="downloadFile(scope.row)">{{ scope.row.fileName }}</a>
                      </template>
                    </el-table-column>
                    <el-table-column label="上传时间" prop="uploadTime">
                      <template #default="scope">
                        <span>
                          {{
                            formatDate(
                              scope.row.uploadTime,
                              "yyyy-MM-dd hh:mm:ss"
                            )
                          }}
                        </span>
                      </template>
                    </el-table-column>
                    <el-table-column label="上传人" prop="uploadUser">
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </div>

            <div class="gva-form-box">
              <div class="w-form-box">
                <div class="list-header">历史修改备注</div>
                <div>
                  <el-table :data="modifyNotes" border style="width: 100%">
                    <el-table-column type="index" label="序号" width="80px" />
                    <el-table-column label="更改内容" prop="reason"></el-table-column>
                    <el-table-column label="更改原因" prop="content">
                    </el-table-column>
                    <el-table-column label="详细说明" prop="detail"></el-table-column>
                    <el-table-column label="更新时间" prop="">
                      <template #default="scope">
                        <span>
                          {{
                            formatDate(
                              scope.row.UpdatedAt,
                              "yyyy-MM-dd hh:mm:ss"
                            )
                          }}
                        </span>
                      </template>
                    </el-table-column>
                    <el-table-column label="更新人" prop="updateUser">
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 相关联配件弹窗 -->
    <el-dialog v-model="contactDialogFormVisible" title="相关联配件" width="800">
      <el-table ref="multipleTableRef" :data="correlationComponentsList" style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <!-- <el-table-column label="Date" width="120">
      <template #default="scope">{{ scope.row.date }}</template>
    </el-table-column> -->
        <el-table-column property="accessoryName" label="配件名称" />
        <el-table-column property="componentNum" label="配件编码" >
          <template #default="scope">
            <span>
              {{ scope.row.componentNum + scope.row.colorNum }}
            </span>
          </template>
        </el-table-column>
        <el-table-column property="num" label="数量" />
        <el-table-column label="尺码">
          <template #default="scope">
            <span>
              {{ scope.row.sizeList?scope.row.sizeList.map((item) => item.sizeNum).join(","):'' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="颜色">
          <template #default="scope">
            <span>
              {{ scope.row.colorList?scope.row.colorList.join(","):'' }}
            </span>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogCel">取消</el-button>
          <el-button type="primary" @click="saveByThree"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- BOM附件长传弹窗 -->
    <el-dialog v-model="uploadDialogVisible" title="文件上传" width="800">
      <el-input v-model="desc" style="width: 100%; margin-bottom: 10px" :rows="3" :maxlength="100" type="textarea"
        placeholder="请输入文件描述" />
      <el-upload :action="`${path}/fileUploadAndDownload/upload`" :on-error="uploadError" drag :on-success="uploadSuccess"
        :headers="{
          'x-token': xToken,
          'x-user-id': xUserId,
          Authorization: `Bearer ${xToken}`,
        }" :show-file-list="false" class="upload-btn">
        <el-button type="primary">上传</el-button>
      </el-upload>
    </el-dialog>

    <!-- 查看内文弹窗 -->
    <el-dialog v-model="textDialogVisible" title="查看内文" width="800">
      <div class="content" style="max-height: 600px; overflow: auto">
        <div v-html="`<div>${textContent}</div>`"></div>

        <!-- <div v-for="item in textContent.accessorySpec">
          <div v-for="it in item">
            <div v-html="`<div>${it}</div>`"></div>
          </div>
        </div>
        <div v-for="item in textContent.sign">
          <div v-for="it in item">
            <div v-html="`<div>${it}</div>`"></div>
          </div>
        </div> -->
      </div>
    </el-dialog>

    <!-- 编辑提交弹窗 -->
    <el-dialog v-model="subDialogFormVisible" title="添加修改备注" width="800">
      <el-form :model="subForm" :rules="subFormRules">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="内容分类：" prop="contentCate">
              <el-checkbox-group v-model="subForm.contentCate">
                <el-checkbox v-for="item in contentCateList" :label="item.label" :value="item.value"
                  style="display: block" />
              </el-checkbox-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="原因分类：" prop="reasonCate">
              <el-checkbox-group v-model="subForm.reasonCate">
                <el-checkbox v-for="item in reasonCateList" :label="item.label" :value="item.value"
                  style="display: block" />
              </el-checkbox-group>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="详细说明" prop="materialNum">
              <el-input type="textarea" :maxlength="200" :clearable="true" placeholder="自定义填写" v-model="subForm.remark" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="subDialogCel">取消</el-button>
          <el-button type="primary" @click="saveByRole"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <toSap ref="toSapRef" :formData="formData" @reloadPageFun="reloadPageFun" :type="'masterBOM'" />
    <styleNumSearch v-if="editReasonDialogShow" @closeDialog="closeDialog" searchType="masterBom"
      @selectStyleNum="selectStyleNum"></styleNumSearch>
  </div>
</template>

<script>
import { onMounted, reactive, toRefs, ref, nextTick, onActivated } from "vue";
import { useRoute, useRouter } from "vue-router";
import UploadCommon from "@/components/upload/common.vue";
import {
  getProductStylesList,
  exportToSapLog,
  exportToSap2,
} from "@/api/plmProductStyles";
import { getProductSpecAccessorySpecList } from "@/api/productSpecAccessorySpec";
import {
  syncMasterBOMAccessorySpec,
  syncMasterBOMAMaterialProperty,
  getLctResult,
  getSapSubBom,
  getInnerText,
  createMasterBOM,
  findMasterBOM,
  updateMasterBOM,
  getPDFurl,
  syncMasterBomProductDocument,
  genMasterBOMListForPackage,
  getMasterBomHistory,
} from "@/api/plmMasterBOM";
import { findProductSpec } from "@/api/plmProductSpec";
import { getDict, useDict } from "@/utils/dictionary";
import { ElMessage, ElMessageBox } from "element-plus";
import { formatDate } from "@/utils/format";
import { emitter } from "@/utils/bus.js";
import createBom from "./createBom.vue";
import toSap from "./toSap.vue";
import { useUserStore } from "@/pinia/modules/user";
import styleNumSearch from "@/components/styleNumSearch/styleNumSearch.vue";
import { useBtnAuth } from "@/utils/btnAuth";
import { deepClone2 } from "@/utils/tool.js";
import router from "@/router";
export default {
  name: "masterBOMAdd",
  components: {
    UploadCommon,
    createBom,
    toSap,
    styleNumSearch,
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const btnAuth = useBtnAuth();
    const state = reactive({
      formData: {
        masterBomNum: "",
        styleNum: "",
        mainMaterial: undefined,
        materialDesc: "",
        storageLocation: "",
        unit: "PC",
        internalNote: "", //内部备注
        status: "",
        materialGroup: "",
        createUesr: "",
        lists: [],
        category: "", //镜架镜片
        costAccountCate: "", //成本核算分类
        gender: "", //性别
        issuanceYear: "", //发型年
        splenicHeadIncisionPosition: "", //脾头切口位
        frameCate: "", //镜架结构
        issuanceMonth: "", //发行月
        hingeType: "", //铰链类别
        version: '',
        ID: undefined,
        FirstCreatedAt:""
      },
      styleNumSelectDetail: {},
      detail: {},
      productSpec: {}, //规格详情
      productStylesList: [], //款式列表
      chengpinzhudangList: [], //成品主档表格
      shipipeijianList: [], //士脾配件
      unitList: [], //单位列表
      componentNumList: [], //原件名称列表
      correlationComponentsList: [], //相关联配件列表
      multipleSelection: [], //相关联配件列表选中项
      threeData: {}, //第三行data暂存
      textDialogVisible: false, //查看内文弹窗
      textContent: {}, //内文详情
      zhaiJiaZhuDangList: [], //斋架主档列表
      type: "create",
      wuliaotexingList: [],
      wuliaotexingList2: [],
      mainMaterialList: [],
      contactDialogFormVisible: false,
      uploadDialogVisible: false, //文件上传弹窗
      desc: "", //文件上传描述
      fullscreenLoading: false, //文件上传loadding
      BOMFileList: [], //文件上传列表
      notes: [{ content: "" }], //BOM备注
      BOMList: [], //bom
      subDialogFormVisible: false,
      subForm: {
        reasonCate: undefined,
        contentCate: undefined,
        remark: "",
      },
      subFormRules: {
        reasonCate: [{ required: true, message: "请选择", trigger: "blur" }],
        contentCate: [{ required: true, message: "请选择", trigger: "blur" }],
      },
      reasonCateList: [], //原因分类
      contentCateList: [], //内容分类
      modifyNotes: [], //历史修改备注
      printBtnLoading: false,
      isView: "1",
      currentRow: null,
      allowClick: true,
      visible: false, //新增包装数量弹窗
      addNum: "1", //新增包装数量
      editReasonDialogShow: false,
      ShiPiPeiJianZhuDangLoading: false,
      fullscreenHandleShow: false,
      version: '',
    });
    const createBomRef = ref(null);

    const PDFViewRef = ref(null);
    // state.isView = route.query.isView;
    state.version = route.query.version && route.query.isBigVersion != 1;
    if (route.query.masterBomNum) {
      state.type = "update";
    }

    // 初始化方法
    const init = async () => {
      // 建议通过url传参获取目标数据ID 调用 find方法进行查询数据操作 从而决定本页面是create还是update 以下为id作为url参数示例
      if (route.query.masterBomNum) {
        let res
        if (route.query.version && route.query.isBigVersion != 1) {
          res = await getMasterBomHistory({ masterBomNum: route.query.masterBomNum, version: route.query.version })
        } else {
          res = await findMasterBOM({ masterBomNum: route.query.masterBomNum });
        }
        if (res.code === 0) {
          let detail = res.data.remasterBOM;
          state.type = "update";
          state.detail = detail;
          for (const key in state.formData) {
            state.formData[key] = detail[key];
          }
          state.styleNumSelectDetail.customerStyleNum =
            detail.customerStyleNum || "";
          state.styleNumSelectDetail.customerBrand = detail.customerBrand || "";
          state.productSpec.metalFrameCate = detail.metalFrameCate || "";
          state.productSpec.sbuNum = detail.sbuNum || "";
          state.styleNumSelectDetail.localStyleNum = detail.localStyleNum || "";
          state.productSpec.frameMaterials = detail.frameMaterials || "";
          state.productSpec.cumstomerNum = detail.cumstomerNum || "";
          state.productSpec.customerBrand = detail.customerBrand || "";
          state.styleNumSelectDetail.standardDesc = detail.standardDesc || "";
          state.styleNumSelectDetail.basicMaterial = detail.basicMaterial || "";
          state.styleNumSelectDetail.series = detail.series || "";
          state.wuliaotexingList = detail.colors || [];
          state.wuliaotexingList2 = detail.sizes || [];
          state.shipipeijianList = detail.accessorySpecs || [];
          state.chengpinzhudangList = detail.productDocuments || [];
          console.log(22222222,state.formData.status);
          nextTick(() => {
            createBomRef.value?.updateData(detail.lists)
          })
          if (state.shipipeijianList.length) {
            addIds(state.shipipeijianList);
            addLevelField(state.shipipeijianList);
            // state.shipipeijianList.forEach(listItem=>{
            //   console.log(listItem)
            //   if(listItem.children){
            //     listItem.children.sort((a,b)=>{
            //       const regex = /[a-z]+$/i; // 匹配一个或多个小写或大写字母，并以字符串末尾结束
            //       const result1 = a.componentNum.match(regex)[0] || '';
            //       const result2 = b.componentNum.match(regex)[0] || '';
            //       if(result1 != result2){
            //         return result1.localeCompare(result2)
            //       }

            //     })
            //   }
            // })
          }
          state.BOMFileList = detail.attachments || [];
          state.notes = detail.notes && detail.notes[0] ? detail.notes : [{ content: "" }];
          if (
            state.productSpec.frameMaterials != "膠架" &&
            state.productSpec.frameMaterials != "啤架"
          ) {
            state.zhaiJiaZhuDangList = detail.frames;
          }
          state.modifyNotes = detail.modifyNotes;
          // 后端要求编辑时候带回去个时间
          state.formData.createUesr = detail.createUesr;
          state.CreatedAt = detail.CreatedAt;

          // 获取原因分类
          getDict("reasonCate").then((res) => {
            state.reasonCateList = res;
          });

          // 获取内容分类
          getDict("contentCate").then((res) => {
            state.contentCateList = res;
          });

          // 新加需求:masterbom是草稿状态时点击编辑进来时重新取一遍值
          if (detail.status == "草稿") {
            remoteMethodProjectStylesAndselect(state.formData.styleNum);
            syncWuLiaoTeXing()
          }
        }
      } else {
        state.type = "create";
      }
      // 获取主原料
      getDict("mainMaterial").then((res) => {
        state.mainMaterialList = res;
      });

      // 获取单位
      getDict("unit").then((res) => {
        state.unitList = res;
      });
    };

    function baseTongbu(params) {
      remoteMethodProjectStylesAndselect(state.formData.styleNum,params);
    }

    // 给树中每个节点增加ids
    function addIds(tree) {
      let level = 1;
      // 递归函数来查找并删除具有给定ID的节点
      function findAndDelete(nodes) {
        if (!nodes || nodes.length === 0) return;

        for (let i = 0; i < nodes.length; i++) {
          nodes[i].ids = Math.random();
          if (nodes[i].children && findAndDelete(nodes[i].children)) {
            // 如果在子节点中找到并删除了节点,则不需要继续遍历
            return true;
          }
        }
      }
      findAndDelete(tree); // 使用数组包装根节点,因为splice影响传入数组
    }

    // 给树中增加层级字段
    function addLevelField(tree, selfLevel = 1) {
      for (let node of tree) {
        node.selfLevel = selfLevel; // 在节点上添加selfLevel字段
        node.lctData = node.lct;
        if (node.children && node.children.length > 0) {
          addLevelField(node.children, selfLevel + 1); // 递归处理子节点
        }
      }
      return tree; // 返回处理后的树
    }

    // 款式发生改变时
    function productStylesChange(params) {
      if (
        state.productStylesList.filter((item) => item.styleNum == params).length
      ) {
        state.styleNumSelectDetail = state.productStylesList.filter(
          (item) => item.styleNum == params
        )[0];
      }
      state.formData["costAccountCate"] = "";
      state.formData["splenicHeadIncisionPosition"] = "";
      state.formData["hingeType"] = "";
      state.formData.materialDesc = "FRAME";
      findProductSpec({ styleNum: params }).then((res) => {
        if (res.code == 0) {
          if (res.data.reproductSpec.ID) {
            state.productSpec = res.data.reproductSpec;
            state.formData.internalNote = state.productSpec.internalNote;
            if (
              state.productSpec.cumstomerNum == "ST101" &&
              state.type == "create"
            ) {
              state.formData.storageLocation = "ST02";
              // state.formData.unit = "PC";
            } else {
              state.formData.storageLocation = "1003";
              // state.formData.unit = "";
            }
          }
          state.formData.materialGroup = getGroup();

          // 新增功能:新增时所有同步按钮自动同步
          syncWuLiaoTeXing("要同步斋架主档");
          if (
            state.productSpec.cumstomerNum == "ST101" ||
            state.productSpec.customerBrand == "LEVIS" ||
            state.productSpec.customerBrand == "levis" ||
            state.productSpec.customerBrand == "fila" ||
            state.productSpec.customerBrand == "FILA"
          ) {
            getChengpinzhudangList();
          }
          syncShiPiPeiJianZhuDang();
        }
      });
    }

    // 获取款式列表
    const remoteMethodProjectStyles = (keyword) => {
      getProductStylesList({
        page: 1,
        pageSize: 50,
        styleNum: keyword ? keyword : undefined,
        status: 1,
        searchType: "masterBom",
        productSpecStatus: 1,
      }).then((res) => {
        if (res.code == 0) {
          state.productStylesList = res.data.list;
        }
      });
    };

    // 获取款式列表并选择具体款式
    const remoteMethodProjectStylesAndselect = (keyword,params) => {
      getProductStylesList({
        page: 1,
        pageSize: 50,
        styleNum: keyword ? keyword : undefined,
        status: 1,
        searchType: "syncMasterBomSync",
        productSpecStatus: 1,
      }).then((res) => {
        if (res.code == 0) {
          if (res.data.list.length) {
            state.styleNumSelectDetail = res.data.list[0];
            if (state.productSpec.cumstomerNum == "ST101") {
              state.detail.standardDesc = state.styleNumSelectDetail.series
              state.detail.basicMaterial = state.styleNumSelectDetail.customerStyleNum
            }
            state.formData.gender =  state.styleNumSelectDetail.gender
            if (!state.shipipeijianList.length) {
              state.shipipeijianList = [
                {
                  componentNum: state.styleNumSelectDetail.localStyleNum,
                  styleNum: state.formData.styleNum,
                  selfLevel: 1,
                  ids: Math.random(),
                },
              ];
            }else{
              state.shipipeijianList[0].componentNum = state.styleNumSelectDetail.localStyleNum || "";
            }
          }
          findProductSpec({ styleNum: keyword }).then((res) => {
            if (res.code == 0) {
              if (res.data.reproductSpec.ID) {
                state.productSpec = res.data.reproductSpec;
                state.formData.internalNote = state.productSpec.internalNote;
              }
              state.formData.materialGroup = getGroup();
             
              if(params) {
                ElMessage({
                type: "success",
                message: "同步基本资料成功",
              });
              }
              
            }
          });
        }
      });
    };

    function back(params) {
      router.go(-1);
    }

    function saveByRole(params) {
      if (!state.subForm.contentCate && !state.subForm.reasonCate) {
        ElMessage({
          type: "warning",
          message: "请输入内容分类和原因分离",
          duration: 2000,
        });
        return;
      }
      saveAsDraft("修改");
    }

    function subAndopenDialog(params) {
      state.subDialogFormVisible = true;
    }

    // 对象数组去重
    function deWeight(arr) {
      for (var i = 0; i < arr.length - 1; i++) {
        for (var j = i + 1; j < arr.length; j++) {
          if (arr[i].sizeNum == arr[j].sizeNum) {
            arr.splice(j, 1);
            //因为数组长度减小1,所以直接 j++ 会漏掉一个元素,所以要 j--
            j--;
          }
        }
      }
      return arr;
    }

    // 同步物料特性
    function syncWuLiaoTeXing(params) {
      syncMasterBOMAMaterialProperty({
        styleNum: state.formData.styleNum,
      }).then((res) => {
        if (res.code == 0) {
          let wuliaoList = JSON.parse(JSON.stringify(res.data.colors || []));
          wuliaoList.forEach((item) => {
            item.colorDesc = "";
            state.wuliaotexingList.forEach((it) => {
              if (item.colorNum == it.colorNum) {
                item.packageNum = it.packageNum;
                item.colorDesc = it.colorDesc;
              }
            });
          });
          state.wuliaotexingList = wuliaoList;

          let wuliaotexingList2 = [];
          res.data.sizes?.forEach((item) => {
            let data1 = {
              sizeNum: item.sizeNum,
              clientSizeDesc: item.clientSizeDesc,
            };
            let data2 = {
              sizeNum: item.sizeNum.split("-")[2],
              clientSizeDesc: item.sizeNum.split("-")[2],
              localSizeDesc: "T" + item.sizeNum.split("-")[2],
            };
            if (
              state.wuliaotexingList2.every((it) => it.sizeNum != data1.sizeNum)
            ) {
              wuliaotexingList2 = wuliaotexingList2.concat(data1, data2);
            } else {
              data1.clientSizeDesc = state.wuliaotexingList2.filter(
                (it) => it.sizeNum == data1.sizeNum
              )[0].clientSizeDesc;
              data2.clientSizeDesc = state.wuliaotexingList2.filter(
                (it) => it.sizeNum == data2.sizeNum
              )[0].clientSizeDesc;
              wuliaotexingList2 = wuliaotexingList2.concat(data1, data2);
            }
          });
          wuliaotexingList2 = deWeight(wuliaotexingList2);
          wuliaotexingList2.sort((a, b) => b.sizeNum.length - a.sizeNum.length);
          state.wuliaotexingList2 = wuliaotexingList2;
          if(params=='手动') {
            ElMessage({
                type: "success",
                message: "同步物料特性成功",
              });
          }
          
          if (
            params=='要同步斋架主档' &&
            state.productSpec.frameMaterials != "膠架" &&
            state.productSpec.frameMaterials != "啤架" &&
            state.wuliaotexingList2.length
          ) {
            syncZhaiJiaZhuDang();
          }
        }
      });
    }

    // 查看内文
    function watchInnerText(params) {
      // getInnerText({
      //   colorNum: params.colorNum,
      //   sizeNum: params.sizeNum,
      //   styleNum: params.styleNum,
      // }).then((res) => {
      //   if (res.code == 0) {
      state.textContent = params.innerText;
      state.textDialogVisible = true;
      //   }
      // });
    }

    // 士脾配件主档----------------------------------------------------------------------------------
    // 同步士脾配件主档
    async function syncShiPiPeiJianZhuDang(params) {
      if (params) {
        state.ShiPiPeiJianZhuDangLoading = true;
        setTimeout(() => {
          state.ShiPiPeiJianZhuDangLoading = false;
          ElMessage({
                type: "success",
                message: "同步士脾配件主档成功",
              });
        }, 1000);
      }
      if (!state.shipipeijianList.length) {
        state.shipipeijianList = [
          {
            componentNum: state.styleNumSelectDetail.localStyleNum,
            styleNum: state.formData.styleNum,
            selfLevel: 1,
            ids: Math.random(),
          },
        ];
      } else {
        state.shipipeijianList[0].componentNum = state.styleNumSelectDetail.localStyleNum || "";
        if (state.shipipeijianList[0].children?.length) {
          let sapSubBomList = [];
          await getSapSubBom({ styleNum: state.formData.styleNum }).then(
            (res) => {
              if (res.code == 0) {
                sapSubBomList = res.data.list;
              }
            }
          );
          state.shipipeijianList[0].children.forEach((item) => {
            blurTest(item, "手动");
            if (item.children?.length) {
              item.children.map((its, idx) => {
                if (its.isPack == "1") {
                  if (its.componentNum) {
                    remoteMethodComponentNum(its.componentNum, its, "手动");
                  }
                } else {
                  if (
                    sapSubBomList.filter((val) => {
                      return its.componentNum.includes(val.componentNum);
                    }).length == 0
                  ) {
                    item.children.splice(idx, 1);
                  } else {
                    let newObj = sapSubBomList.filter((val) => {
                      return its.componentNum.includes(val.componentNum);
                    })[0];
                    its.componentNum = newObj.componentNum + newObj.colorNum;
                    its.accessoryName = newObj.accessoryName;
                    its.lct = newObj.lct;
                    its.lctData = newObj.lct;
                    its.group = newObj.group;
                    its.sapDesc = newObj.sapDesc;
                    its.num = String(newObj.num);
                    its.unit = newObj.unit;
                    its.selectList =
                      newObj.ringFootMaterials?.length > 1
                        ? newObj.ringFootMaterials
                        : null;
                    its.sortLetter =
                      newObj.ringFootMaterials?.length == 1
                        ? newObj.ringFootMaterials[0].ringOrFoot
                        : undefined;
                  }
                }
              });
            }
          });
        }
      }
     
    }
    // 士脾配件主档第一层新增
    function levelOneAdd(data) {
      let arr = {
        componentNum: "",
        group: "",
        lct: "",
        sapDesc: "",
        num: "1",
        standardDesc:
          state.productSpec.cumstomerNum == "ST101"
            ? state.styleNumSelectDetail.series
            : "",
        unit: undefined,
        selfLevel: 2,
        ids: Math.random(),
      };
      if (!data.children) {
        data.children = [arr];
      } else {
        data.children.push(arr);
      }
    }

    // 删除第树结构中某项
    function deleteRow(tree, ids) {
      if (state.shipipeijianList[0].ids == ids) {
        ElMessage({
          type: "warning",
          message: "第一层不可删除!",
        });
        return;
      }
      // 递归函数来查找并删除具有给定ID的节点
      function findAndDelete(nodes) {
        if (!nodes || nodes.length === 0) return;

        for (let i = 0; i < nodes.length; i++) {
          if (nodes[i].ids === ids) {
            nodes.splice(i, 1); // 删除节点
            return true; // 找到并删除后退出
          }
          if (nodes[i].children && findAndDelete(nodes[i].children)) {
            // 如果在子节点中找到并删除了节点,则不需要继续遍历
            return true;
          }
        }
      }

      findAndDelete(tree); // 使用数组包装根节点,因为splice影响传入数组
    }
    const arraySpanMethod = ({ row, column, rowIndex, columnIndex }) => {
      if (rowIndex == 0) {
        return [1, 8];
      }
    };
    // 基础信息的物料群组
    function getGroup(params) {
      if (state.productSpec.cumstomerNum == "ST101") {
        if (state.productSpec.frameMaterials == "金架") {
          //金架

          if (
            state.styleNumSelectDetail.glassFrameCate == "配光架" ||
            state.styleNumSelectDetail.glassFrameCate == "老花架"
          ) {
            return "20008";
          } else if (
            state.styleNumSelectDetail.glassFrameCate == "掛架" ||
            state.styleNumSelectDetail.glassFrameCate == "太陽架"
          ) {
            return `20012`;
          }

          // return new Array("","20008", "20012");
          //return @Explode("20008,20012");
        }
        if (state.productSpec.frameMaterials == "膠架") {
          //膠架
          if (
            state.styleNumSelectDetail.glassFrameCate == "配光架" ||
            state.styleNumSelectDetail.glassFrameCate == "老花架"
          ) {
            return "20009";
          } else if (
            state.styleNumSelectDetail.glassFrameCate == "掛架" ||
            state.styleNumSelectDetail.glassFrameCate == "太陽架"
          ) {
            return `20011`;
          }
          // return new Array("","20009", "20011");
          //return @Explode("20009,20011");
        }
        if (state.productSpec.frameMaterials == "啤架") {
          //啤架
          if (
            state.styleNumSelectDetail.glassFrameCate == "配光架" ||
            state.styleNumSelectDetail.glassFrameCate == "老花架"
          ) {
            return "20043";
          } else if (
            state.styleNumSelectDetail.glassFrameCate == "掛架" ||
            state.styleNumSelectDetail.glassFrameCate == "太陽架"
          ) {
            return `20044`;
          }
          // return new Array("","20043", "20044");
          //return @Explode("20043,20044");
        }
        if (state.productSpec.frameMaterials == "鈦架") {
          //鈦架
          if (
            state.styleNumSelectDetail.glassFrameCate == "配光架" ||
            state.styleNumSelectDetail.glassFrameCate == "老花架"
          ) {
            return "20021";
          } else if (
            state.styleNumSelectDetail.glassFrameCate == "掛架" ||
            state.styleNumSelectDetail.glassFrameCate == "太陽架"
          ) {
            return `20051`;
          }
          // return new Array("","20021", "20051");
          //return @Explode("20021,20051");
        }
        if (state.productSpec.frameMaterials == "鋁架") {
          //鋁架
          if (
            state.styleNumSelectDetail.glassFrameCate == "配光架" ||
            state.styleNumSelectDetail.glassFrameCate == "老花架"
          ) {
            return "20045";
          } else if (
            state.styleNumSelectDetail.glassFrameCate == "掛架" ||
            state.styleNumSelectDetail.glassFrameCate == "太陽架"
          ) {
            return `20050`;
          }
          // return new Array("","20045", "20050");
          //return @Explode("20045,20050");
        }
        if (state.productSpec.frameMaterials == "掛架") {
          //掛架
          return "20010";
        }
        if (state.productSpec.frameMaterials == "記憶架") {
          //記憶架
          if (
            state.styleNumSelectDetail.glassFrameCate == "配光架" ||
            state.styleNumSelectDetail.glassFrameCate == "老花架"
          ) {
            return "20048";
          } else if (
            state.styleNumSelectDetail.glassFrameCate == "掛架" ||
            state.styleNumSelectDetail.glassFrameCate == "太陽架"
          ) {
            return `20049`;
          }
          // return new Array("","20048", "20049");
          //return @Explode("20048,20049");
        }
        if (state.productSpec.frameMaterials == "混合架") {
          //混合架
          if (
            state.styleNumSelectDetail.glassFrameCate == "配光架" ||
            state.styleNumSelectDetail.glassFrameCate == "老花架"
          ) {
            return "20046";
          } else if (
            state.styleNumSelectDetail.glassFrameCate == "掛架" ||
            state.styleNumSelectDetail.glassFrameCate == "太陽架"
          ) {
            return `20047`;
          }
          // return new Array("","20046", "20047");
          //return @Explode("20046,20047");
        }
        if (state.productSpec.frameMaterials == "中金架") {
          //中金架(金-不需釘鉸)
          if (
            state.styleNumSelectDetail.glassFrameCate == "配光架" ||
            state.styleNumSelectDetail.glassFrameCate == "老花架"
          ) {
            return "20019";
          } else if (
            state.styleNumSelectDetail.glassFrameCate == "掛架" ||
            state.styleNumSelectDetail.glassFrameCate == "太陽架"
          ) {
            return `20052`;
          }
          // return new Array("","20019", "20052");
          //return @Explode("20019,20052");
        }
      } else {
        if (state.productSpec.frameMaterials == "金架") {
          //金架
          return "20001";
        }
        if (state.productSpec.frameMaterials == "膠架") {
          //膠架
          return "20002";
        }
        if (state.productSpec.frameMaterials == "啤架") {
          //啤架
          return "20022";
        }
        if (state.productSpec.frameMaterials == "鈦架") {
          //鈦架
          return "20004";
        }
        if (state.productSpec.frameMaterials == "鋁架") {
          //鋁架
          return "20036";
        }
        if (state.productSpec.frameMaterials == "掛架") {
          //掛架
          return "20005";
        }
        if (state.productSpec.frameMaterials == "記憶架") {
          //記憶架
          return "20042";
        }
        if (state.productSpec.frameMaterials == "混合架") {
          //混合架
          return "20037";
        }
        if (state.productSpec.frameMaterials == "中金架") {
          //中金架(金-不需釘鉸)
          return "20003";
        }
      }
    }
    // 获取士脾配件主档2层物料群组
    function getGroup2(params) {
      if (!params) {
        return;
      }
      if (!params.split("-")[2]) {
        return;
      }
      let ElementByFittings = params.split("-")[2];
      let secondItem = params.split("-")[1];
      if (state.productSpec.cumstomerNum == "ST101") {
        if (/^\d{3}[a-zA-Z]$/.test(ElementByFittings)) {
          return "20018";
        } else if (/^T\d{3}[a-zA-Z]$/.test(ElementByFittings)) {
          return "20039";
        } else if (/^T\d{3}$/.test(ElementByFittings)) {
          return "20039";
        } else if (ElementByFittings == "FORMERS") {
          return "20029";
        } else if (ElementByFittings == "TIPS") {
          if (/^\d{2}[a-zA-Z]$/.test(secondItem)) {
            return "20024";
          }
        } else if (/^NA\d{1}$/.test(ElementByFittings)) {
          return "20034";
        } else if (/^TR\d{1}$/.test(ElementByFittings)) {
          return "20038";
        } else if (ElementByFittings == "DEMOLENS") {
          return "20025";
        } else if (ElementByFittings == "SUNLENS") {
          if (/^\d{2}[a-zA-Z]$/.test(secondItem)) {
            return "20026";
          }
        } else if (/^NP[a-zA-Z]$/.test(ElementByFittings)) {
          return "20027";
        } else if (ElementByFittings.indexOf("PA") == 0) {
          return "20062";
        } else if (/^SC[a-zA-Z]$/.test(ElementByFittings)) {
          return "20028";
        } else if (/^FR\d{2}[a-zA-Z]$/.test(ElementByFittings)) {
          return "20035";
        } else if (ElementByFittings == "BOOK") {
          return "20040";
        } else if (/^DC.*/.test(ElementByFittings)) {
          return "20033";
        } else if (/^CD.*/.test(ElementByFittings)) {
          return "20030";
        }
      } else {
        if (ElementByFittings.indexOf("TP") != -1) {
          return "20024";
        }
        if (ElementByFittings.indexOf("DL") != -1) {
          return "20025";
        }
        if (ElementByFittings.indexOf("SL") != -1) {
          return "20026";
        }
        if (ElementByFittings.indexOf("NP") != -1) {
          return "20027";
        }
        if (ElementByFittings.indexOf("SC") != -1) {
          return `20028,20061`;
        }
        if (ElementByFittings.indexOf("FO") != -1) {
          return "20029";
        }
        if (ElementByFittings.indexOf("CD") != -1) {
          return "20030";
        }
        if (ElementByFittings.indexOf("HT") != -1) {
          return "20031";
        }
        if (ElementByFittings.indexOf("CE") != -1) {
          return "20032";
        }
        if (ElementByFittings.indexOf("DC") != -1) {
          return "20033";
        }
        if (ElementByFittings.indexOf("NA") != -1) {
          return "20034";
        }
        if (ElementByFittings.indexOf("FR") != -1) {
          return "20035";
        }
        if (ElementByFittings.indexOf("TR") != -1) {
          return "20038";
        }
        if (ElementByFittings.indexOf("TM") != -1) {
          return "20039";
        }
        if (ElementByFittings.indexOf("BOOK") != -1) {
          return "20040";
        }
        if (ElementByFittings.indexOf("RC") != -1) {
          return "20041";
        }
        if (ElementByFittings.indexOf("PB") != -1) {
          return "20060";
        }

        if (ElementByFittings.indexOf("PA") != -1) {
          return "20062";
        }
        if (ElementByFittings.indexOf("MT") != -1) {
          return "20063";
        }

        if (ElementByFittings.indexOf("T") != -1) {
          return "20039";
        }
      }
    }

    // 成品主档物料群组
    function getMaterialGroupOptions(row) {
      if (row.variableSettingSize.split("-").length > 1) {
        row.materialGroup = state.formData.materialGroup;
        if (state.productSpec.cumstomerNum == "ST101") {
          if (state.productSpec.frameMaterials == "金架") {
            //金架
            return ["20008", "20012"];
          } else if (state.productSpec.frameMaterials == "膠架") {
            //膠架
            return ["20009", "20011"];
          } else if (state.productSpec.frameMaterials == "啤架") {
            //啤架
            return ["20043", "20044"];
          } else if (state.productSpec.frameMaterials == "鈦架") {
            //鈦架
            return ["20021", "20051"];
          } else if (state.productSpec.frameMaterials == "鋁架") {
            //鋁架
            return ["20045", "20050"];
          } else if (state.productSpec.frameMaterials == "掛架") {
            //掛架
            return ["20010"];
          } else if (state.productSpec.frameMaterials == "記憶架") {
            //記憶架
            return ["20048", "20049"];
          } else if (state.productSpec.frameMaterials == "混合架") {
            //混合架
            return ["20046", "20047"];
          } else if (state.productSpec.frameMaterials == "中金架") {
            //中金架(金-不需釘鉸)
            return ["20019", "20052"];
          }
        } else {
          if (
            state.productSpec.customerBrand == "LEVIS" ||
            state.productSpec.customerBrand == "levis" ||
            state.productSpec.customerBrand == "fila" ||
            state.productSpec.customerBrand == "FILA"
          ) {
            return [`${state.formData.materialGroup}`];
          }
        }
      } else {
        if (state.productSpec.cumstomerNum == "ST101") {
          row.materialGroup = "20018";
          return ["20018"];
        } else {
          if (
            state.productSpec.customerBrand == "LEVIS" ||
            state.productSpec.customerBrand == "levis" ||
            state.productSpec.customerBrand == "fila" ||
            state.productSpec.customerBrand == "FILA"
          ) {
            row.materialGroup = "20017";
            return ["20017"];
          }
        }
      }
    }

    // 元件编号校验
    const blurTest = (item, mode) => {
      let flag = /^[0-9A-Za-z]{1,15}-[0-9A-Za-z]{1,15}-[0-9A-Za-z]{1,15}$/.test(
        item.componentNum
      );
      if (!flag) {
        item["err"] = "请输入合规的编号";
        item.componentNum = "";
        return false
      } else {
        item["err"] = undefined;
        let sapDesc = getTwoWuliaoshuoming(item.componentNum);
        if(sapDesc) {
          item.sapDesc = sapDesc
        }
        if (getGroup2(item.componentNum)?.split(",").length > 1) {
          item.groupList = getGroup2(item.componentNum).split(",");
          item.group = getGroup2(item.componentNum).split(",")[0];
        } else if(getGroup2(item.componentNum)?.split(",").length == 1) {
          item.group = getGroup2(item.componentNum);
        }
        if (!mode) {
          getLctResult({
            componentNum: item.componentNum,
            group: item.group,
          }).then((res) => {
            item.lctData = res.data.result;
            item.lct = res.data.result;
          });
        }
        return true
      }
    };

    // 第二层的物料说明生成
    function getTwoWuliaoshuoming(componentNum) {
      let sapDesc = "";
      if (!state.styleNumSelectDetail.localStyleNum) {
        return;
      } else {
        let ElementByFittings = componentNum.split("-")[2];
        let secondItem = componentNum.split("-")[1];
        if (state.productSpec.cumstomerNum == "ST101") {
          if (/^\d{2}[a-zA-Z]$/.test(ElementByFittings)) {
            if (
              state.wuliaotexingList2.filter(
                (item) =>
                  item.sizeNum.indexOf(ElementByFittings.slice(0, 2)) != -1
              ).length &&
              state.wuliaotexingList.filter(
                (item) => item.colorNum == ElementByFittings.slice(2)
              ).length
            ) {
              sapDesc = `${state.wuliaotexingList2.filter(
                (item) =>
                  item.sizeNum.indexOf(ElementByFittings.slice(0, 2)) != -1
              )[0].sizeNum
                },${state.wuliaotexingList.filter(
                  (item) => item.colorNum == ElementByFittings.slice(2)
                )[0].customerStyleNum},${state.wuliaotexingList2.filter(
                (item) =>
                  item.sizeNum.indexOf(ElementByFittings.slice(0, 2)) != -1
              )[0].sizeNum
                },${state.wuliaotexingList.filter(
                  (item) => item.colorNum == ElementByFittings.slice(2)
                )[0].customerColorNum
                }`;
            }
          } else if (/^\d{3}[a-zA-Z]$/.test(ElementByFittings)) {
            if (
              state.wuliaotexingList.filter(
                (item) => item.colorNum == ElementByFittings.slice(3)
              ).length
            ) {
              sapDesc = `${state.wuliaotexingList.filter(
                  (item) => item.colorNum == ElementByFittings.slice(3)
                )[0].customerStyleNum
                },TEMPLE,${state.wuliaotexingList.filter(
                  (item) => item.colorNum == ElementByFittings.slice(3)
                )[0].customerColorNum
                }`;
            }
          } else if (/^T\d{3}[a-zA-Z]$/.test(ElementByFittings)) {
            if (
              state.wuliaotexingList.filter(
                (item) => item.colorNum == ElementByFittings.slice(4)
              ).length
            ) {
              sapDesc = `${state.wuliaotexingList.filter(
                  (item) => item.colorNum == ElementByFittings.slice(3)
                )[0].customerStyleNum
                },SPARE TEMPLE,${state.wuliaotexingList.filter(
                  (item) => item.colorNum == ElementByFittings.slice(4)
                )[0].customerColorNum
                }`;
            }
          } else if (/^T\d{3}$/.test(ElementByFittings)) {
            sapDesc = `${state.styleNumSelectDetail.customerStyleNum},SPARE TEMPLE`;
          } else if (ElementByFittings == "FORMERS") {
            sapDesc = `${state.styleNumSelectDetail.customerStyleNum},SPARE FORMERS`;
          } else if (ElementByFittings == "TIPS") {
            if (/^\d{2}[a-zA-Z]$/.test(secondItem)) {
              if (
                state.wuliaotexingList.filter(
                  (item) => item.colorNum == secondItem.slice(2)
                ).length
              ) {
                sapDesc = `${state.wuliaotexingList.filter(
                  (item) => item.colorNum == secondItem.slice(2)
                )[0].customerStyleNum},${state.wuliaotexingList.filter(
                  (item) => item.colorNum == secondItem.slice(2)
                )[0].customerColorNum
                  },TIPS`;
              }
            }
          } else if (/^NA\d{1}$/.test(ElementByFittings)) {
            sapDesc = `${state.styleNumSelectDetail.customerStyleNum},SPARE BRIDGE`;
          } else if (/^TR\d{1}$/.test(ElementByFittings)) {
            sapDesc = `${state.styleNumSelectDetail.customerStyleNum},SPARE TRIM`;
          } else if (ElementByFittings == "DEMOLENS") {
            sapDesc = `${state.styleNumSelectDetail.customerStyleNum},DEHOLENS`;
          } else if (ElementByFittings == "SUNLENS") {
            if (/^\d{2}[a-zA-Z]$/.test(secondItem)) {
              sapDesc = `${state.wuliaotexingList.filter(
                (item) => item.colorNum == secondItem.slice(2)
              )[0].customerStyleNum},${state.wuliaotexingList.filter(
                (item) => item.colorNum == secondItem.slice(2)
              )[0].customerColorNum
                },SUNLENS`;
            }
          } else if (/^NP[a-zA-Z]$/.test(ElementByFittings)) {
            if (
              state.wuliaotexingList.filter(
                (item) => item.colorNum == ElementByFittings.slice(2)
              ).length
            ) {
              sapDesc = `Argon X,SPARE NOSE PAD,${state.wuliaotexingList.filter(
                (item) => item.colorNum == ElementByFittings.slice(2)
              )[0].customerColorNum
                }`;
            }
          } else if (ElementByFittings.indexOf("PA") == 0) {
          } else if (/^SC[a-zA-Z]$/.test(ElementByFittings)) {
            if (
              state.wuliaotexingList.filter(
                (item) => item.colorNum == ElementByFittings.slice(2)
              ).length
            ) {
              sapDesc = `${state.wuliaotexingList.filter(
                  (item) => item.colorNum == ElementByFittings.slice(2)
                )[0].customerStyleNum
                },SPARE SCREWS,${state.wuliaotexingList.filter(
                  (item) => item.colorNum == ElementByFittings.slice(2)
                )[0].customerColorNum
                }`;
            }
          } else if (/^FR\d{2}[a-zA-Z]$/.test(ElementByFittings)) {
            if (
              state.wuliaotexingList.filter(
                (item) => item.colorNum == ElementByFittings.slice(4)
              ).length
            ) {
              sapDesc = `Argon X, SPARE FRONT,${state.wuliaotexingList.filter(
                (item) => item.colorNum == ElementByFittings.slice(4)
              )[0].customerColorNum
                }`;
            }
          } else if (ElementByFittings == "BOOK") {
            sapDesc = `${state.styleNumSelectDetail.customerStyleNum},SPARE BOOKLET`;
          } else if (/^DC.*/.test(ElementByFittings)) {
            sapDesc = `${state.styleNumSelectDetail.customerStyleNum},SPARE DRILL CHART`;
          } else if (/^CD.*/.test(ElementByFittings)) {
            sapDesc = `${state.styleNumSelectDetail.customerStyleNum},SPARE CARDS`;
          }
        } else {
          if (!isPass(componentNum)) {
            return
          }
          // if()
          
          if (
            state.wuliaotexingList.filter(
              (item) =>
                item.colorNum == componentNum.charAt(componentNum.length - 1)
            ).length
          ) {
            sapDesc += `${state.wuliaotexingList.filter(
              (item) =>
                item.colorNum == componentNum.charAt(componentNum.length - 1)
            )[0].customerStyleNum
              },${state.wuliaotexingList.filter(
              (item) =>
                item.colorNum == componentNum.charAt(componentNum.length - 1)
            )[0].customerColorNum
              }`;
          }else {
            sapDesc += state.styleNumSelectDetail.customerStyleNum;
          }
          let eng = componentNum.split("-")[2].substring(0, 2);
          if (eng == "TP") {
            sapDesc += `,Spare Tips`;
          } else if (eng == "DL") {
            sapDesc += `,Spare Demo Lens`;
          } else if (eng == "SL") {
            sapDesc += `,Spare Sun Lens`;
          } else if (eng == "NP") {
            sapDesc += `,Spare Nose Pad`;
          } else if (eng == "FO") {
            sapDesc += `,Spare Formers`;
          } else if (eng == "CD") {
            sapDesc += `,Spare Cards`;
          } else if (eng == "HT") {
            sapDesc += `,Spare Hang Tags`;
          } else if (eng == "CE") {
            sapDesc += `,Spare Case`;
          } else if (eng == "DC") {
            sapDesc += `,Spare Drill Chart`;
          } else if (eng == "NA") {
            sapDesc += `,Spare Bridge`;
          } else if (eng == "FR") {
            sapDesc += `,Spare Front`;
          } else if (eng == "TR") {
            sapDesc += `,Spare Trim`;
          } else if (eng == "T") {
            sapDesc += `,Spare Temple`;
          } else if (componentNum.split("-")[2] == "BOOK") {
            sapDesc += `,Spare Booklet`;
          } else if (eng == "RC") {
            sapDesc += `,Spare Ribbon/Cords`;
          } else if (eng == "PB") {
            sapDesc += `,Spare Poly Bag`;
          } else if (eng == "PA") {
            sapDesc += `,Spare Metal Trim`;
          } else if (eng == "MT") {
            sapDesc += `,Spare Pad Arm`;
          } 
        }
        return sapDesc;
      }
    }

    // 判断第二层的元件编号不是ST101情况下是否可以生成物料说明
    function isPass(componentNum) {
      let disanduan = componentNum.split("-")[2]
      let eng = componentNum.split("-")[2].substring(0, 2);
      if (componentNum.includes(state.styleNumSelectDetail.localStyleNum) &&
        (eng == "TP" || eng == "DL" || eng == "SL" || eng == "NP" || eng == "FO" || eng == "CD" || eng == "HT" || eng == "CE" || eng == "DC" || eng == "NA" || eng == "FR" || eng == "TR"
          || componentNum.split("-")[2].substring(0, 1) == "T" || componentNum.split("-")[2].substring(0, 4) == "BOOK" || eng == "RC" || eng == "PB" || eng == "PA" || eng == "MT" || eng == "SC"
        )) {
        return true
      } else {
        return false
      }
    }


    // 获取原件编号列表
    const remoteMethodComponentNum = (keyword, item, mode) => {
      genMasterBOMListForPackage({
        componentNum: keyword ? keyword : undefined,
      }).then((res) => {
        if (res.code == 0) {
          item.componentNum = res.data.componentNum;
          item.accessoryName = res.data.accessoryName;
          item.group = res.data.group;
          item.lct = mode ? item.lct : res.data.lct;
          item.lctData = item.lct;
          item.sapDesc = res.data.standardDesc;
          item.standardDesc = res.data.standardDesc;
          item.unit = res.data.unit;
          item.isPack = "1";

          item.num =  String(item.num);
        } else {
          item.componentNum = "";
          item.accessoryName = "";
          item.group = "";
          item.lct = "";
          item.lctData = "";
          item.sapDesc = "";
          item.num = "1";
          item.standardDesc = "";
          item.unit = undefined;
          item.isPack = "1";
          item.selectList = null;
          item.sortLetter = "";
        }
      });
    };

    // 点击加包装
    function addPackage(data) {
      for (let index = 0; index < state.addNum; index++) {
        let arr = {
          componentNum: "",
          group: "",
          lct: "",
          lctData: "",
          sapDesc: "",
          num: null,
          standardDesc: "",
          unit: undefined,
          selfLevel: 3,
          ids: Math.random(),
          isPack: "1",
        };

        if (!data.children) {
          data.children = [arr];
        } else {
          data.children.push(arr);
        }
      }
      state.addNum = "1";
    }

    // 点击加配件
    function addAccessory(data) {
      state.threeData = data;
      getSapSubBom({ styleNum: state.formData.styleNum }).then((res) => {
        if (res.code == 0) {
          state.contactDialogFormVisible = true;
          state.correlationComponentsList = res.data.list;
          if(state.correlationComponentsList){
            state.correlationComponentsList.sort((a,b)=>{
              let c1 = ''
              let c2 = ''
              if (a.colorList && a.colorList[0]) {
                  c1 = a.colorList[0]
              }
              if (b.colorList && b.colorList[0]) {
                  c2 = b.colorList[0]
              }
              let a1 = (a.componentNum || '') + (a.colorNum || '')
              let b1 = (b.componentNum || '') + (b.colorNum || '')
              if (a.listOrder !== b.listOrder) {
                  return a.listOrder - b.listOrder;
              } else if (c1 != c2) {
                  return c1.localeCompare(c2);
              } else if (a1 != b1) {
                  return a1.localeCompare(b1);
              }
            })
          }
        }
      });
    }

    const handleSelectionChange = (val) => {
      state.multipleSelection = val;
    };

    // 弹窗取消
    function dialogCel(params) {
      state.multipleSelection = [];
      state.contactDialogFormVisible = false;
    }

    // 弹窗确定
    function saveByThree() {
      if (!state.multipleSelection.length) {
        return;
      }
      state.multipleSelection.forEach((item) => {
        if (!state.threeData.children) {
          state.threeData.children = [
            {
              componentNum: item.componentNum + item.colorNum,
              accessoryName: item.accessoryName,
              lct: item.lct,
              lctData: item.lct,
              group: item.group,
              sapDesc: item.sapDesc,
              num: String(item.num),
              unit: item.unit,
              selectList:
                item.ringFootMaterials?.length > 1
                  ? item.ringFootMaterials
                  : null,
              sortLetter:
                item.ringFootMaterials?.length == 1
                  ? item.ringFootMaterials[0].ringOrFoot
                  : undefined,
              selfLevel: 3,
              ids: Math.random(),
              isPack: "0",
            },
          ];
        } else {
          state.threeData.children.push({
            componentNum: item.componentNum + item.colorNum,
            accessoryName: item.accessoryName,
            lct: item.lct,
            lctData: item.lct,
            group: item.group,
            sapDesc: item.sapDesc,
            num: item.num,
            unit: item.unit,
            selectList:
              item.ringFootMaterials?.length > 1
                ? item.ringFootMaterials
                : null,
            sortLetter:
              item.ringFootMaterials?.length == 1
                ? item.ringFootMaterials[0].ringOrFoot
                : undefined,
            selfLevel: 3,
            ids: Math.random(),
            isPack: "0",
          });
        }
      });
      dialogCel();
    }

    const handleCurrentChange = (val) => {
      state.currentRow = val;
    };

    function downloadTemplate(params) {
      const path1 = ref(import.meta.env.VITE_BASE_PATH);
      const File = '/download/baozhuang.xlsx'
      var xml = new XMLHttpRequest()
      xml.open('GET', path1.value + File, true)
      xml.responseType = 'blob'
      xml.onload = function () {
        var url = window.URL.createObjectURL(xml.response)
        var a = document.createElement('a')
        a.href = url
        a.download = '士啤配件导入主档及包装物料.xlsx'
        a.click()
      }
      xml.send()
    }

    // 限制只能上传excel
    function beforeUpload(file) {
      //获取上传文件
      let formData = new FormData(); //FormData对象,添加参数只能通过append('key', value)的形式添加
      formData.append("file", file); //添加文件对象
      const Xls = file.name.split(".")[file.name.split(".").length - 1];
      if (Xls === "xls" || Xls === "xlsx" || Xls === "csv") {
        return file;
      } else {
        ElMessage({
          type: "error",
          message: "请上传excel格式的文件!",
        });
        // ElMessage.error("请上传excel格式的文件!");
        return false;
      }
    }

    const shipipeijianDataUploadSuccess = (res) => {
      if (res.code == 0) {
        const { data } = res;
        if (!state.shipipeijianList[0].children) {
          state.shipipeijianList[0].children = []
        }
        for (const key in data) {
          blurTest(data[key], '手动')
          state.shipipeijianList[0].children.push(data[key])
        }
        addIds(state.shipipeijianList);
        addLevelField(state.shipipeijianList);
      } else {
        ElMessage({
          type: "error",
          message: res.msg,
        });
      }
    };

    // BOM上传---------------------------------------------------------------
    const path = ref(import.meta.env.VITE_BASE_API);
    const userStore = useUserStore();
    const xToken = ref("");
    const xUserId = ref("");
    xToken.value = userStore.token;
    xUserId.value = userStore.userInfo.ID;
    function openUploadDialog(params) {
      state.uploadDialogVisible = true;
    }

    const uploadSuccess = (res) => {
      const { data } = res;
      if (data.file) {
        let datas = {
          desc: state.desc,
          fileUrl: data.file.url,
          uploadTime: data.file.CreatedAt,
          uploadUser: data.file.uploadUser,
          fileName: data.file.name,
        };
        state.BOMFileList.push(datas);
        ElMessage({
          type: "success",
          message: "上传成功",
        });
        state.uploadDialogVisible = false;
        state.desc = "";
      }
    };

    const uploadError = () => {
      ElMessage({
        type: "error",
        message: "上传失败",
      });
      state.fullscreenLoading = false;
    };

    const downloadFile = (row) => {
      let newUrl = "";
      if (
        row.fileUrl.indexOf("http://") > -1 ||
        row.fileUrl.indexOf("https://") > -1
      ) {
        newUrl = row.fileUrl;
      } else {
        newUrl = path.value + "/" + row.fileUrl;
      }

      const x = new XMLHttpRequest()
      x.open('GET', newUrl, true)
      x.responseType = 'blob'
      x.onload = e => {
        // 会创建一个 DOMString,其中包含一个表示参数中给出的对象的URL。这个 URL 的生命周期和创建它的窗口中的 document 绑定。这个新的URL 对象表示指定的 File 对象或 Blob 对象。
        const url = window.URL.createObjectURL(x.response)
        const a = document.createElement('a')
        a.href = url
        a.download = row.name || "photo"
        a.click()
      }
      x.send()
    };

    // BOM备注---------------------------------------------------------------
    function asyncRemark(params) {
        findProductSpec({styleNum:state.formData.styleNum}).then((res) => {
          if(res.code==0){
            if (res.data.reproductSpec.styleNote) {
              state.content = res.data.reproductSpec.styleNote;
              state.notes = [{ content: res.data.reproductSpec.styleNote }];
            }
            ElMessage({
              type: "success",
              message: "同步产品规格备注成功",
            });
          }
        })
    }

    // 斋架主档---------------------------------------------------------------
    //  同步斋架主档
    function syncZhaiJiaZhuDang(params) {
      // state.zhaiJiaZhuDangList = [];
      let newZhaiJiaZhuDangList = [];
      state.wuliaotexingList2.forEach((item, index) => {
        let flag =
          /^[0-9A-Za-z]{1,15}-[0-9A-Za-z]{1,15}-[0-9A-Za-z]{1,15}$/.test(
            item.sizeNum
          );

        if (flag) {
          let data1 = {
            lct: "F",
            componentNum:
              state.styleNumSelectDetail.localStyleNum +
              "-" +
              item.sizeNum.split("-")[0],
            group: "30001",
            strategyGroup: "10",
            num: "1",
            unit: "PC",
            materialDesc: "",
            strategyGroupList: true,
          };
          let data2 = {
            lct: "F",
            componentNum:
              state.styleNumSelectDetail.localStyleNum +
              "-" +
              item.sizeNum.split("-")[2],
            group: "30012",
            strategyGroup: "10",
            num: "1",
            unit: "PR",
            materialDesc: "",
          };

          // 要求如果编号重了,就不改策略群组,数量,单位,物料说明
          if (
            state.zhaiJiaZhuDangList.filter(
              (item) => data1.componentNum == item.componentNum).length
          ) {
            data1.strategyGroup = state.zhaiJiaZhuDangList.filter(
              (item) => data1.componentNum == item.componentNum
            )[0].strategyGroup;
            data1.num = state.zhaiJiaZhuDangList.filter(
              (item) => data1.componentNum == item.componentNum
            )[0].num;
            data1.unit = state.zhaiJiaZhuDangList.filter(
              (item) => data1.componentNum == item.componentNum
            )[0].unit;
            data1.materialDesc = state.zhaiJiaZhuDangList.filter(
              (item) => data1.componentNum == item.componentNum
            )[0].materialDesc;
          }
          if (
            state.zhaiJiaZhuDangList.filter(
              (item) => data2.componentNum == item.componentNum
            ).length
          ) {
            data2.strategyGroup = state.zhaiJiaZhuDangList.filter(
              (item) => data2.componentNum == item.componentNum
            )[0].strategyGroup;
            data2.num = state.zhaiJiaZhuDangList.filter(
              (item) => data2.componentNum == item.componentNum
            )[0].num;
            data2.unit = state.zhaiJiaZhuDangList.filter(
              (item) => data2.componentNum == item.componentNum
            )[0].unit;
            data2.materialDesc = state.zhaiJiaZhuDangList.filter(
              (item) => data2.componentNum == item.componentNum
            )[0].materialDesc;
          }

          // 要求编号重复就不加进去了
          if (
            newZhaiJiaZhuDangList.every((item) => {
              return data1.componentNum != item.componentNum;
            })
          ) {
            newZhaiJiaZhuDangList.unshift(data1);
          }
          if (
            newZhaiJiaZhuDangList.every((item) => {
              return data2.componentNum != item.componentNum;
            })
          ) {
            newZhaiJiaZhuDangList.push(data2);
          }


        }
      });
      state.zhaiJiaZhuDangList = newZhaiJiaZhuDangList;
      if(params) {
        ElMessage({
                type: "success",
                message: "斋架主档成功",
              });
      }
      
    }

    // 创建BOM-------------------------------------------------------------------
    function createBOM(params) {
      if (
        state.productSpec.frameMaterials != "膠架" &&
        state.productSpec.frameMaterials != "啤架"
      ) {
        if (!state.styleNumSelectDetail.costAccountCate) {
          ElMessage({
            type: "error",
            message: "成本核算分类填写不完整!",
          });
          return;
        }
        if (!state.styleNumSelectDetail.splenicHeadIncisionPosition) {
          ElMessage({
            type: "error",
            message: "脾头切口位填写不完整!",
          });
          return;
        }
        if (!state.styleNumSelectDetail.hingeType) {
          ElMessage({
            type: "error",
            message: "铰链类别填写不完整!",
          });
          return;
        }
      } else {
      }
    }

    // 获取成品主档
    function getChengpinzhudangList(params) {
      syncMasterBomProductDocument({ styleNum: state.formData.styleNum }).then(
        (res) => {
          if (res.code == 0) {
            state.chengpinzhudangList = res.data.map((item) => {
              if (item.variableSettingSize.indexOf("-") > -1) {
                item.materialGroup = state.formData.materialGroup;
              } else {
                if (state.productSpec.cumstomerNum == "ST101") {
                  item.materialGroup = "20018";
                } else {
                  item.materialGroup = "20017";
                }
              }
              // 新需求,点同步,保留以前填的数据
              //  if(state.chengpinzhudangList.filter(val=>val.variableSettingSize==item.variableSettingSize).length) {
              //   item.materialGroup= state.chengpinzhudangList.filter(val=>val.variableSettingSize==item.variableSettingSize)[0].materialGroup
              // }
              return item;
            });
            if(params) {
              ElMessage({
                type: "success",
                message: "同步成品主档成功",
              });
            }
            
          }
        }
      );
    }
    function resData(list){
      list.forEach(item=>{
        item.num = item.num? String(item.num) : ''
        item.num = item.num.trim()
        if(item.children){
          resData(item.children)
        }
      })
    }

    //保存/提交
    function saveAsDraft(params, params2, params3) {
      if (!state.formData.styleNum) {
        ElMessage({
          type: "warning",
          message: "请选择款式编号",
        });
        return;
      }
      if (!state.allowClick) {
        return;
      } else {
        state.allowClick = false;
        setTimeout(() => {
          state.allowClick = true;
        }, 3000);
      }
      let ll = deepClone2(createBomRef.value?.tableData) || []
      resData(ll)
      let datas = {
        ...state.formData,
        masterBomNum: state.formData.masterBomNum, //masterbom编号
        customerStyleNum: state.styleNumSelectDetail.customerStyleNum, //客户款号
        customerBrand: state.styleNumSelectDetail.customerBrand, //品牌
        metalFrameCate: state.productSpec.metalFrameCate, //中金架类
        sbuNum: state.productSpec.sbuNum, //SBU
        localStyleNum: state.styleNumSelectDetail.localStyleNum, //本厂款号
        frameMaterials: state.productSpec.frameMaterials, //材质架类
        cumstomerNum: state.productSpec.cumstomerNum, //客户编号
        standardDesc: "", //标准说明
        basicMaterial: "", //基本物料
        series: state.styleNumSelectDetail.series, //系列
        FirstCreatedAt:state.formData.FirstCreatedAt,
        colors: state.wuliaotexingList.map(
          ({
            colorNum,
            customerColorNum,
            customerStyleNum,
            localStyleDesc,
            brand,
            colorDesc,
            packageNum,
            salesNum,
            ID,
            innerText,
          }) => ({
            colorNum,
            customerColorNum,
            customerStyleNum,
            localStyleDesc,
            brand,
            colorDesc,
            packageNum,
            salesNum,
            ID,
            innerText,
          })
        ),

        sizes: state.wuliaotexingList2.map(
          ({ sizeNum, clientSizeDesc, localSizeDesc, ID }) => ({
            sizeNum,
            clientSizeDesc,
            localSizeDesc,
            ID,
          })
        ),
        accessorySpecs: state.shipipeijianList,
        attachments: state.BOMFileList,
        notes: state.notes
          .map(item => {
            item.content = item.content.replace(/[ ]/g, '').replace(/(\r\n|\r|\n)\s*(\r\n|\r|\n)/g, '$1')
            return item
          })
        ,
        productDocuments: state.chengpinzhudangList,
        lists: ll,
      };
      if (
        state.productSpec.frameMaterials != "膠架" &&
        state.productSpec.frameMaterials != "啤架"
      ) {
        datas.frames = state.zhaiJiaZhuDangList.map((item) => {
          item.num = String(item.num);
          return item;
        });
      }


      if (state.type == "create") {
        datas.standardDesc =
          state.productSpec.cumstomerNum == "ST101"
            ? state.styleNumSelectDetail.series
            : "";

        datas.basicMaterial =
          state.productSpec.cumstomerNum == "ST101"
            ? state.styleNumSelectDetail.customerStyleNum
            : "";

        if (params == "保存") {
          datas.isDraft = "是";
          datas.issapimported = "否";
        } else if (params == "提交") {
          datas.isDraft = "否";
          datas.issapimported = "否";

          // 校验士脾配件主档的数量和单位
          let shipipeijianListAllowSub = true;
          if (state.shipipeijianList[0].children?.length) {
            state.shipipeijianList[0].children.forEach((item) => {
              if (!item.num || Number(item.num) <= 0 || !item.unit) {
                shipipeijianListAllowSub = false;
              }
              if (item.children?.length) {
                item.children.map((its, idx) => {
                  if (!its.num || Number(its.num) <= 0 || !its.unit) {
                    shipipeijianListAllowSub = false;
                  }
                });
              }
            });
          }
          if (!shipipeijianListAllowSub) {
            ElMessage({
              type: "warning",
              message: "士啤配件主档数量需大于0、单位不能为空!",
            });
            return;
          }

          // // 校验斋架主档的数量和单位和物料说明
          // let zhaiJiaZhuDangListAllowSub = true;
          // state.zhaiJiaZhuDangList.forEach((item) => {
          //   if (
          //     !item.num ||
          //     item.num <= 0 ||
          //     !item.unit ||
          //     !item.materialDesc
          //   ) {
          //     zhaiJiaZhuDangListAllowSub = false;
          //   }
          // });

          // if (!zhaiJiaZhuDangListAllowSub) {
          //   ElMessage({
          //     type: "warning",
          //     message: "斋架主档数量需大于0、单位、物料说明不能为空!",
          //   });
          //   return;
          // }

          // 校验创建BOM的数量
          // let listsAllowSub = true;
          // datas.lists?.forEach((item) => {
          //   if (!item.num || Number(item.num) <= 0) {
          //     listsAllowSub = false;
          //   }
          // });

          // if (!listsAllowSub) {
          //   ElMessage({
          //     type: "warning",
          //     message: "Bom数量需大于0!",
          //   });
          //   return;
          // }
        }

        createMasterBOM(datas).then((res) => {
          if (res.code == 0) {
            ElMessage({
              type: "success",
              message: "创建成功",
            });
            emitter.emit("closeThisPage");
            // 获取当前URL
            const currentUrl = new URL(window.location.href);
            window.location.href =
              currentUrl.href +
              "?ID=" +
              res.data.ID +
              "&subTitle=" +
              res.data.localStyleNum + "&masterBomNum=" +
              res.data.masterBomNum;
          }
        });
      } else {
        if (params3 == "toSap") {
          
       let list =  datas.lists.filter(item=>{
            return item.is_pack==1
        })
        let liststate;
        list.forEach(item=>{
          if(  !item.sizeList || item.sizeList?.length==0  ){
            
            if(!item.includedAngleList || item.includedAngleList?.length==0 ){
              liststate=true
            }
          }
          if( !item.colorList|| item.colorList?.length==0 ){
            liststate=true
          }
          
        })
        if(liststate==true){
          ElMessage({
              type: "error",
              message: "BOM的包裝物料要关联尺码和颜色，才能能汇入SAP",
            });
          return
        }
        
          // 校验士脾配件主档的数量和单位
          let shipipeijianListAllowSub = true;
          if (state.shipipeijianList[0].children?.length) {
            state.shipipeijianList[0].children.forEach((item) => {
              if (!item.num || Number(item.num) <= 0 || !item.unit) {
                shipipeijianListAllowSub = false;
              }
              if (item.children?.length) {
                item.children.map((its, idx) => {
                  if (!its.num || Number(its.num) <= 0 || !its.unit) {
                    shipipeijianListAllowSub = false;
                  }
                });
              }
            });
          }
          if (!shipipeijianListAllowSub) {
            ElMessage({
              type: "warning",
              message: "士啤配件主档数量需大于0、单位不能为空!",
            });
            return;
          }

          // 校验斋架主档的数量和单位和物料说明
          let zhaiJiaZhuDangListAllowSub = true;
          state.zhaiJiaZhuDangList.forEach((item) => {
            if (
              !item.num ||
              item.num <= 0 ||
              !item.unit ||
              !item.materialDesc
            ) {
              zhaiJiaZhuDangListAllowSub = false;
            }
          });

          if (!zhaiJiaZhuDangListAllowSub) {
            ElMessage({
              type: "warning",
              message: "斋架主档数量需大于0、单位、物料说明不能为空!",
            });
            return;
          }

          // 校验创建BOM的数量
          let listsAllowSub = true;
          datas.lists?.forEach((item) => {
            if (!item.num || Number(item.num) <= 0) {
              listsAllowSub = false;
            }
          });

          if (!listsAllowSub) {
            ElMessage({
              type: "warning",
              message: "Bom数量需大于0!",
            });
            return;
          }
        }
        datas.standardDesc =
          state.productSpec.cumstomerNum == "ST101"
            ? state.detail.standardDesc
            : "";
        datas.basicMaterial =
          state.productSpec.cumstomerNum == "ST101"
            ? state.detail.basicMaterial
            : "";
        if (datas.status == "草稿") {
          if (params == "保存") {
            datas.isDraft = "是";
            datas.issapimported = "否";
          } else if (params == "提交") {
            datas.isDraft = "否";
            datas.issapimported = "否";
          }
        } else if (datas.status == "已確認") {
          if (params == "保存") {
            datas.isDraft = "否";
            datas.issapimported = "否";
          }
        } else if (datas.status == "已匯入SAP") {
          if (params == "修改") {
            datas.isDraft = "是";
            datas.issapimported = "否";
            datas.modifyNotes = [
              {
                content: state.subForm.contentCate?.join(","),
                reason: state.subForm.reasonCate?.join(","),
                detail: state.subForm.remark || "",
              },
            ];
          }
        }
        datas.CreatedAt = state.CreatedAt; //后端要求编辑时候往回传个CreatedAt
        datas.ID = Number(state.formData.ID);
        updateMasterBOM(datas).then((res) => {
          if (res.code == 0) {
            ElMessage({
              type: "success",
              message:
                params == "提交"
                  ? "提交成功"
                  : params == "保存"
                    ? "保存成功"
                    : "修改成功",
            });
            if (params == "保存") {
              init();
              if (params3) {
                toSapRef.value.toSap();
              }
            } else if (params == '修改') {
              state.subDialogFormVisible = false;
              init()
            } else {
              emitter.emit("closeThisPage");
              router.push("/layout/masterBOM");
            }
          }
        });
      }
    }

    // 关闭提交弹窗
    function subDialogCel(params) {
      state.subForm = {
        reasonCate: undefined,
        contentCate: undefined,
        materialNum: "",
      };
      state.subDialogFormVisible = false;
    }

    // 打印
    function print(params) {
      state.printBtnLoading = true;
      getPDFurl({ ID: Number(state.formData.ID) }).then((res) => {
        state.printBtnLoading = false;
        const link = document.createElement("a");
        link.href = import.meta.env.VITE_BASE_PATH + "/" + res.data.fileUrl;
        link.download = link.href.split("/")[link.href.split("/").length - 1];
        // link.target = "_blank"; // 可选,如果希望在新窗口中下载文件,请取消注释此行
        link.click();
      });
    }

    function formEdit(params) {
      // console.log(32432);
      // // 获取当前URL
      // const currentUrl = new URL(window.location.href);
      // emitter.emit("closeThisPage");
      // window.location.href =
      //   currentUrl.origin +
      //   "/#" +
      //   route.path +
      //   "?subTitle=" +
      //   route.query.subTitle + "&masterBomNum=" +
      //   route.query.masterBomNum;
        state.isView='0'
    }

    let sapParam = ref({
      steps: "",
      factoryCode: "",
      stepList: [
        { label: "1、成品主档", value: "step1" },
        { label: "2、颜色特性", value: "step2" },
        { label: "3、尺码特性", value: "step3" },
        { label: "4、分类", value: "step4" },
        { label: "5、相关联", value: "step5" },
        { label: "6、变式", value: "step6" },
        { label: "7、后复色成品主档", value: "step7" },
        { label: "8、士啤配件主档", value: "step8" },
        { label: "9、士啤配件 BOM", value: "step9" },
        { label: "10、斋架主档", value: "step10" },
        { label: "11、斋架配件 BOM", value: "step11" },
        { label: "12、成品自制配件 BOM", value: "step12" },
        { label: "13、成品 BOM", value: "step13" },
        { label: "14、可设定物料连接", value: "step14" },
        { label: "15、配件做色要求", value: "step15" },
      ],
    });
    const toSapRef = ref();
    function toSap() {
      saveAsDraft("保存", "提交", "toSap");
    }
    function getParams() {
      let params = {
        ID: state.formData.ID,
        getParam: 1,
        steps: sapParam.value.steps,
        factoryCode: sapParam.value.factoryCode,
      };
      exportToSap2(params, "/masterBOM/exportToSap")
        .then((res) => {
          const path1 = import.meta.env.VITE_BASE_API + "/";
          const fileUrl = path1 + res.data.fileUrl;
          // const link = document.createElement("a");
          // link.href = fileUrl;
          // let name =
          //   res.data.fileUrl.split("/")[res.data.fileUrl.split("/").length - 1];
          // link.setAttribute("download", name);
          // link.click();
          const x = new XMLHttpRequest();
          x.open("GET", fileUrl, true);
          x.responseType = "blob";
          x.onload = (e) => {
              let { status, readyState } = x;
              if (status === 200 && readyState === 4) {
                  // 会创建一个 DOMString，其中包含一个表示参数中给出的对象的URL。这个 URL 的生命周期和创建它的窗口中的 document 绑定。这个新的URL 对象表示指定的 File 对象或 Blob 对象。
                  const url = window.URL.createObjectURL(x.response);
                  const a = document.createElement("a");
                  a.href = url;
                  let name = res.data.fileUrl.split("/")[res.data.fileUrl.split("/").length - 1];
                  a.download = name;
                  a.click();
              } else {
                  if (status === 404) {
                      ElMessage({
                          type: "warning",
                          message: "文件不存在",
                      });
                  } else {
                      ElMessage({
                          type: "warning",
                          message: "下载出错",
                      });
                  }
              }
          };
          x.send();
        })
        .catch((err) => {
          console.log("err===>", err);
        });
    }

    // 从款式挪过来9个基础信息
    // 字典列表
    const dictOptions = ref({
      establishOrder: [], //開辦順序
      glassFrameCate: [], //镜架结构
      drawer: [], // 绘图
      frameCate: [], // 款式資訊-架類
      styleCate: [], // 款式資訊-類別
      costAccountCate: [], //成本核算分類
      frameMaterials: [], //镜架材质
      productGender: [], //款式資訊-性別
      splenicHeadIncisionPosition: [], //脾頭切口位
      hingeType: [], //鉸鏈類別
      businessCate: [], //業務類別
      issuanceMonth: [], //業務月
      issuanceYear: [], //業務年
      transferOrder: [], // 转单
    });

    // 款式查询弹窗
    // 打开 新增、编辑
    const openCreateAndEdit = () => {
      state.editReasonDialogShow = true;
    };

    // 关闭款式查询弹窗
    function closeDialog(params) {
      state.editReasonDialogShow = false;
    }

    function selectStyleNum(params) {
      state.formData.styleNum = params.styleNum;
      productStylesChange(params.styleNum);
      state.editReasonDialogShow = false;
    }
    function reloadPageFun() {
      init();
      // state.isView = 1
    }

    // 聚焦全选
    function handleFocus(e) {
      e.target.select()
    }


    onMounted(async () => {
      init();
      const dict = await useDict(
        "establishOrder",
        "glassFrameCate",
        "drawer",
        "frameCate",
        "styleCate",
        "costAccountCate",
        "frameMaterials",
        "productGender",
        "splenicHeadIncisionPosition",
        "hingeType",
        "businessCate",
        "issuanceYear",
        "issuanceMonth",
        "transferOrder"
      );
      dictOptions.value = Object.assign(dictOptions.value, dict);
    });

    onActivated(async () => {
      init();
      const dict = await useDict(
        "establishOrder",
        "glassFrameCate",
        "drawer",
        "frameCate",
        "styleCate",
        "costAccountCate",
        "frameMaterials",
        "productGender",
        "splenicHeadIncisionPosition",
        "hingeType",
        "businessCate",
        "issuanceYear",
        "issuanceMonth",
        "transferOrder"
      );
      dictOptions.value = Object.assign(dictOptions.value, dict);
    })

    return {
      ...toRefs(state),
      route,
      path,
      productStylesChange,
      back,
      saveByRole,
      subAndopenDialog,
      syncShiPiPeiJianZhuDang,
      syncWuLiaoTeXing,
      arraySpanMethod,
      levelOneAdd,
      blurTest,
      deleteRow,
      remoteMethodComponentNum,
      addPackage,
      addAccessory,
      handleSelectionChange,
      dialogCel,
      openUploadDialog,
      uploadSuccess,
      uploadError,
      asyncRemark,
      downloadFile,
      formatDate,
      saveByThree,
      getGroup,
      syncZhaiJiaZhuDang,
      watchInnerText,
      // componentNumChange,
      createBOM,
      remoteMethodProjectStyles,
      saveAsDraft,
      subDialogCel,
      print,
      getChengpinzhudangList,
      createBomRef,
      handleCurrentChange,
      xToken,
      xUserId,
      formEdit,
      toSap,
      toSapRef,
      getParams,
      sapParam,
      dictOptions,
      openCreateAndEdit,
      closeDialog,
      selectStyleNum,
      baseTongbu,
      btnAuth,
      userStore,
      getGroup2,
      getMaterialGroupOptions,
      downloadTemplate,
      beforeUpload,
      shipipeijianDataUploadSuccess,
      reloadPageFun,
      handleFocus
    };
  },
};
</script>

<style lang="scss" scoped>
.form-header {
  font-size: 22px;
  font-weight: 600;
  background: #fff;
  padding: 20px;
  border-bottom: 1px solid #ccc5;
}

.form-box {
  margin: 0 auto;
}

.form-footer {
  text-align: center;
  margin-top: 20px;
}

.jianlishipipeijianzhudang {
  :deep(.el-select__suffix) {
    display: none;
  }

  :deep(.cell) {
    display: flex;
    align-items: center;
  }

  :deep(.el-select__wrapper) {
    padding: 4px;
  }
}

:deep(.el-tree) {
  >.el-tree-node {
    >.el-tree-node__content {
      height: unset !important;
    }

    >.el-tree-node__children {
      >.el-tree-node {
        margin-bottom: 10px;

        >.el-tree-node__content {
          height: unset !important;
        }

        >.el-tree-node__children {
          height: unset !important;
          margin-top: 10px;

          >.el-tree-node {
            margin-bottom: 10px;

            >.el-tree-node__content {
              height: unset !important;
            }
          }

          &:hover {
            background-color: unset;
          }
        }
      }

      &:hover {
        background-color: unset;
      }
    }
  }

  // &:hover {
  //   background-color: unset;
  // }
}

.custom-table-header {
  display: flex;
  align-items: center;
  background-color: #f7fbff;
  border: 1px solid rgb(232 234 236);
  color: rgb(55 65 81);
  font-weight: bold;

  >div {
    padding: 14px 0px;
    padding-left: 10px;
    border-right: 1px solid rgb(232 234 236);
    flex: 10;
  }
}

:deep(.el-descriptions__label) {
  min-width: 100px !important;
}

:deep(.el-descriptions__cell) {
  min-width: 100px !important;

  .el-date-editor.el-input,
  .el-date-editor.el-input__wrapper {
    width: unset;
    min-width: 120px;
  }
}
</style>

<style lang="scss" scoped>
@import url("@/style/common/common.scss");

.header {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-box {
  display: flex;
  align-items: center;

  .title {
    font-size: 20px;
    font-weight: 600;
    margin-right: 8px;
  }
}

.sap-log {
  word-break: break-word;
  flex: 0 0 50%;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.fullscreen-handle1 {
  padding: 20px;
  box-sizing: border-box;
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100%;
  height: 100%;
  z-index: 1500;
  background: #fff;

  :deep(.el-scrollbar__wrap) {
    height: calc(100vh - 108px);
    overflow: scroll;
  }
}
:deep(
        .el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell
    ) {
    background: #f8fb8a !important;
}
</style>
